There are memory leaks in production on queries that trigger a full scan. Review all queries for missing close and other bugs that could cause memory leaks in the sqlite-3 driver. Example for a query that triggers a massive allocation is a specific jobstate list with sorting on start_time on all jobs.


I'll explore the query-related code in the repository to find potential memory leaks.


Agent

Find SQL query patterns and rows handling

Prompt:
Very thoroughly explore the database query code in this Go project for potential memory leaks related to SQLite3. Focus on:

1. All files in `internal/repository/` - read every .go file (not _test.go) completely
2. Any place where `db.Query`, `db.QueryRow`, `db.QueryContext`, `sq.Query`, `squirrel` query builder `.Query()` is called
3. Look for patterns where `rows` from queries are NOT properly closed with `defer rows.Close()` or `rows.Close()`
4. Look for patterns where errors between `Query()` and the row scanning loop could cause rows to not be closed
5. Look for any `sql.Rows` that could leak - especially in error paths
6. Check if there are any unbounded queries (no LIMIT) that could cause massive memory allocation
7. Look at how the squirrel query builder is used - particularly `RunWith()` and whether results are properly handled

Read all .go files in internal/repository/ completely. Also check internal/graph/schema.resolvers.go and internal/api/ for any direct DB access.


Very thoroughly explore the database query code in this Go project for potential memory leaks related to SQLite3. Focus on:

1. All files in `internal/repository/` - read every .go file (not _test.go) completely
2. Any place where `db.Query`, `db.QueryRow`, `db.QueryContext`, `sq.Query`, `squirrel` query builder `.Query()` is called
3. Look for patterns where `rows` from queries are NOT properly closed with `defer rows.Close()` or `rows.Close()`
4. Look for patterns where errors between `Query()` and the row scanning loop could cause rows to not be closed
5. Look for any `sql.Rows` that could leak - especially in error paths
6. Check if there are any unbounded queries (no LIMIT) that could cause massive memory allocation
7. Look at how the squirrel query builder is used - particularly `RunWith()` and whether results are properly handled

Read all .go files in internal/repository/ completely. Also check internal/graph/schema.resolvers.go and internal/api/ for any direct DB access.

Prompt:
Very thoroughly explore the database query code in this Go project for potential memory leaks related to SQLite3. Focus on:

1. All files in `internal/repository/` - read every .go file (not _test.go) completely
2. Any place where `db.Query`, `db.QueryRow`, `db.QueryContext`, `sq.Query`, `squirrel` query builder `.Query()` is called
3. Look for patterns where `rows` from queries are NOT properly closed with `defer rows.Close()` or `rows.Close()`
4. Look for patterns where errors between `Query()` and the row scanning loop could cause rows to not be closed
5. Look for any `sql.Rows` that could leak - especially in error paths
6. Check if there are any unbounded queries (no LIMIT) that could cause massive memory allocation
7. Look at how the squirrel query builder is used - particularly `RunWith()` and whether results are properly handled

Read all .go files in internal/repository/ completely. Also check internal/graph/schema.resolvers.go and internal/api/ for any direct DB access.


Bash

find /Users/jan/prg/CC/cc-backend/internal/repository -type f -name "*.go" | head -20


find /Users/jan/prg/CC/cc-backend/internal/repository -type f -name "*.go" ! -name "*_test.go" | sort


     1→// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.
     2→// All rights reserved. This file is part of cc-backend.
     3→// Use of this source code is governed by a MIT-style
     4→// license that can be found in the LICENSE file.
     5→
     6→package repository
     7→
     8→import (
     9→	"database/sql"
    10→	"fmt"
    11→	"net/url"
    12→	"sync"
    13→	"time"
    14→
    15→	cclog "github.com/ClusterCockpit/cc-lib/v2/ccLogger"
    16→	"github.com/jmoiron/sqlx"
    17→	"github.com/mattn/go-sqlite3"
    18→	"github.com/qustavo/sqlhooks/v2"
    19→)
    20→
    21→var (
    22→	dbConnOnce     sync.Once
    23→	dbConnInstance *DBConnection
    24→)
    25→
    26→type DBConnection struct {
    27→	DB     *sqlx.DB
    28→	Driver string
    29→}
    30→
    31→type DatabaseOptions struct {
    32→	URL                   string
    33→	MaxOpenConnections    int
    34→	MaxIdleConnections    int
    35→	ConnectionMaxLifetime time.Duration
    36→	ConnectionMaxIdleTime time.Duration
    37→}
    38→
    39→func setupSqlite(db *sql.DB) error {
    40→	pragmas := []string{
    41→		"temp_store = memory",
    42→	}
    43→
    44→	for _, pragma := range pragmas {
    45→		_, err := db.Exec("PRAGMA " + pragma)
    46→		if err != nil {
    47→			return err
    48→		}
    49→	}
    50→
    51→	return nil
    52→}
    53→
    54→func Connect(db string) {
    55→	var err error
    56→	var dbHandle *sqlx.DB
    57→
    58→	dbConnOnce.Do(func() {
    59→		opts := DatabaseOptions{
    60→			URL:                   db,
    61→			MaxOpenConnections:    repoConfig.MaxOpenConnections,
    62→			MaxIdleConnections:    repoConfig.MaxIdleConnections,
    63→			ConnectionMaxLifetime: repoConfig.ConnectionMaxLifetime,
    64→			ConnectionMaxIdleTime: repoConfig.ConnectionMaxIdleTime,
    65→		}
    66→
    67→		// TODO: Have separate DB handles for Writes and Reads
    68→		// Optimize SQLite connection: https://kerkour.com/sqlite-for-servers
    69→		connectionURLParams := make(url.Values)
    70→		connectionURLParams.Add("_txlock", "immediate")
    71→		connectionURLParams.Add("_journal_mode", "WAL")
    72→		connectionURLParams.Add("_busy_timeout", "5000")
    73→		connectionURLParams.Add("_synchronous", "NORMAL")
    74→		connectionURLParams.Add("_cache_size", "1000000000")
    75→		connectionURLParams.Add("_foreign_keys", "true")
    76→		opts.URL = fmt.Sprintf("file:%s?%s", opts.URL, connectionURLParams.Encode())
    77→
    78→		if cclog.Loglevel() == "debug" {
    79→			sql.Register("sqlite3WithHooks", sqlhooks.Wrap(&sqlite3.SQLiteDriver{}, &Hooks{}))
    80→			dbHandle, err = sqlx.Open("sqlite3WithHooks", opts.URL)
    81→		} else {
    82→			dbHandle, err = sqlx.Open("sqlite3", opts.URL)
    83→		}
    84→
    85→		if err != nil {
    86→			cclog.Abortf("DB Connection: Could not connect to SQLite database with sqlx.Open().\nError: %s\n", err.Error())
    87→		}
    88→
    89→		err = setupSqlite(dbHandle.DB)
    90→		if err != nil {
    91→			cclog.Abortf("Failed sqlite db setup.\nError: %s\n", err.Error())
    92→		}
    93→
    94→		dbHandle.SetMaxOpenConns(opts.MaxOpenConnections)
    95→		dbHandle.SetMaxIdleConns(opts.MaxIdleConnections)
    96→		dbHandle.SetConnMaxLifetime(opts.ConnectionMaxLifetime)
    97→		dbHandle.SetConnMaxIdleTime(opts.ConnectionMaxIdleTime)
    98→
    99→		dbConnInstance = &DBConnection{DB: dbHandle}
   100→		err = checkDBVersion(dbHandle.DB)
   101→		if err != nil {
   102→			cclog.Abortf("DB Connection: Failed DB version check.\nError: %s\n", err.Error())
   103→		}
   104→	})
   105→}
   106→
   107→func GetConnection() *DBConnection {
   108→	if dbConnInstance == nil {
   109→		cclog.Fatalf("Database connection not initialized!")
   110→	}
   111→
   112→	return dbConnInstance
   113→}
   114→
   115→// ResetConnection closes the current database connection and resets the connection state.
   116→// This function is intended for testing purposes only to allow test isolation.
   117→func ResetConnection() error {
   118→	if dbConnInstance != nil && dbConnInstance.DB != nil {
   119→		if err := dbConnInstance.DB.Close(); err != nil {
   120→			return fmt.Errorf("failed to close database connection: %w", err)
   121→		}
   122→	}
   123→
   124→	dbConnInstance = nil
   125→	dbConnOnce = sync.Once{}
   126→	jobRepoInstance = nil
   127→	jobRepoOnce = sync.Once{}
   128→	nodeRepoInstance = nil
   129→	nodeRepoOnce = sync.Once{}
   130→	userRepoInstance = nil
   131→	userRepoOnce = sync.Once{}
   132→	userCfgRepoInstance = nil
   133→	userCfgRepoOnce = sync.Once{}
   134→
   135→	return nil
   136→}
   137→


     1→// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.
     2→// All rights reserved. This file is part of cc-backend.
     3→// Use of this source code is governed by a MIT-style
     4→// license that can be found in the LICENSE file.
     5→
     6→package repository
     7→
     8→import (
     9→	"context"
    10→	"database/sql"
    11→	"fmt"
    12→	"time"
    13→
    14→	"github.com/ClusterCockpit/cc-backend/internal/graph/model"
    15→	cclog "github.com/ClusterCockpit/cc-lib/v2/ccLogger"
    16→	"github.com/ClusterCockpit/cc-lib/v2/schema"
    17→	sq "github.com/Masterminds/squirrel"
    18→)
    19→
    20→// Find executes a SQL query to find a specific batch job.
    21→// The job is queried using the batch job id, the cluster name,
    22→// and the start time of the job in UNIX epoch time seconds.
    23→// It returns a pointer to a schema.Job data structure and an error variable.
    24→// To check if no job was found test err == sql.ErrNoRows
    25→func (r *JobRepository) Find(
    26→	jobID *int64,
    27→	cluster *string,
    28→	startTime *int64,
    29→) (*schema.Job, error) {
    30→	if jobID == nil {
    31→		return nil, fmt.Errorf("jobID cannot be nil")
    32→	}
    33→
    34→	start := time.Now()
    35→	q := sq.Select(jobColumns...).From("job").
    36→		Where("job.job_id = ?", *jobID)
    37→
    38→	if cluster != nil {
    39→		q = q.Where("job.cluster = ?", *cluster)
    40→	}
    41→	if startTime != nil {
    42→		q = q.Where("job.start_time = ?", *startTime)
    43→	}
    44→
    45→	q = q.OrderBy("job.id DESC").Limit(1) // always use newest matching job by db id if more than one match
    46→
    47→	cclog.Debugf("Timer Find %s", time.Since(start))
    48→	return scanJob(q.RunWith(r.stmtCache).QueryRow())
    49→}
    50→
    51→// FindCached executes a SQL query to find a specific batch job from the job_cache table.
    52→// The job is queried using the batch job id, and optionally filtered by cluster name
    53→// and start time (UNIX epoch time seconds). This method uses cached job data which
    54→// may be stale but provides faster access than Find().
    55→// It returns a pointer to a schema.Job data structure and an error variable.
    56→// To check if no job was found test err == sql.ErrNoRows
    57→func (r *JobRepository) FindCached(
    58→	jobID *int64,
    59→	cluster *string,
    60→	startTime *int64,
    61→) (*schema.Job, error) {
    62→	if jobID == nil {
    63→		return nil, fmt.Errorf("jobID cannot be nil")
    64→	}
    65→
    66→	q := sq.Select(jobCacheColumns...).From("job_cache").
    67→		Where("job_cache.job_id = ?", *jobID)
    68→
    69→	if cluster != nil {
    70→		q = q.Where("job_cache.cluster = ?", *cluster)
    71→	}
    72→	if startTime != nil {
    73→		q = q.Where("job_cache.start_time = ?", *startTime)
    74→	}
    75→
    76→	q = q.OrderBy("job_cache.id DESC").Limit(1) // always use newest matching job by db id if more than one match
    77→
    78→	return scanJob(q.RunWith(r.stmtCache).QueryRow())
    79→}
    80→
    81→// FindAll executes a SQL query to find all batch jobs matching the given criteria.
    82→// Jobs are queried using the batch job id, and optionally filtered by cluster name
    83→// and start time (UNIX epoch time seconds).
    84→// It returns a slice of pointers to schema.Job data structures and an error variable.
    85→// An empty slice is returned if no matching jobs are found.
    86→func (r *JobRepository) FindAll(
    87→	jobID *int64,
    88→	cluster *string,
    89→	startTime *int64,
    90→) ([]*schema.Job, error) {
    91→	if jobID == nil {
    92→		return nil, fmt.Errorf("jobID cannot be nil")
    93→	}
    94→
    95→	start := time.Now()
    96→	q := sq.Select(jobColumns...).From("job").
    97→		Where("job.job_id = ?", *jobID)
    98→
    99→	if cluster != nil {
   100→		q = q.Where("job.cluster = ?", *cluster)
   101→	}
   102→	if startTime != nil {
   103→		q = q.Where("job.start_time = ?", *startTime)
   104→	}
   105→
   106→	rows, err := q.RunWith(r.stmtCache).Query()
   107→	if err != nil {
   108→		cclog.Errorf("Error while running FindAll query for jobID=%d: %v", *jobID, err)
   109→		return nil, fmt.Errorf("failed to execute FindAll query: %w", err)
   110→	}
   111→	defer rows.Close()
   112→
   113→	jobs := make([]*schema.Job, 0, 10)
   114→	for rows.Next() {
   115→		job, err := scanJob(rows)
   116→		if err != nil {
   117→			cclog.Warnf("Error while scanning rows in FindAll: %v", err)
   118→			return nil, fmt.Errorf("failed to scan job row: %w", err)
   119→		}
   120→		jobs = append(jobs, job)
   121→	}
   122→	cclog.Debugf("Timer FindAll %s", time.Since(start))
   123→	return jobs, nil
   124→}
   125→
   126→// GetJobList returns job IDs for non-running jobs.
   127→// This is useful to process large job counts and intended to be used
   128→// together with FindById to process jobs one by one.
   129→// Use limit and offset for pagination. Use limit=0 to get all results (not recommended for large datasets).
   130→func (r *JobRepository) GetJobList(limit int, offset int) ([]int64, error) {
   131→	query := sq.Select("id").From("job").
   132→		Where("job.job_state != 'running'")
   133→
   134→	// Add pagination if limit is specified
   135→	if limit > 0 {
   136→		query = query.Limit(uint64(limit)).Offset(uint64(offset))
   137→	}
   138→
   139→	rows, err := query.RunWith(r.stmtCache).Query()
   140→	if err != nil {
   141→		cclog.Errorf("Error while running GetJobList query (limit=%d, offset=%d): %v", limit, offset, err)
   142→		return nil, fmt.Errorf("failed to execute GetJobList query: %w", err)
   143→	}
   144→	defer rows.Close()
   145→
   146→	jl := make([]int64, 0, 1000)
   147→	for rows.Next() {
   148→		var id int64
   149→		err := rows.Scan(&id)
   150→		if err != nil {
   151→			cclog.Warnf("Error while scanning rows in GetJobList: %v", err)
   152→			return nil, fmt.Errorf("failed to scan job ID: %w", err)
   153→		}
   154→		jl = append(jl, id)
   155→	}
   156→
   157→	cclog.Debugf("JobRepository.GetJobList(): Return job count %d", len(jl))
   158→	return jl, nil
   159→}
   160→
   161→// FindByID executes a SQL query to find a specific batch job.
   162→// The job is queried using the database id.
   163→// It returns a pointer to a schema.Job data structure and an error variable.
   164→// To check if no job was found test err == sql.ErrNoRows
   165→func (r *JobRepository) FindByID(ctx context.Context, jobID int64) (*schema.Job, error) {
   166→	q := sq.Select(jobColumns...).
   167→		From("job").Where("job.id = ?", jobID)
   168→
   169→	q, qerr := SecurityCheck(ctx, q)
   170→	if qerr != nil {
   171→		return nil, qerr
   172→	}
   173→
   174→	return scanJob(q.RunWith(r.stmtCache).QueryRow())
   175→}
   176→
   177→// FindByIDWithUser executes a SQL query to find a specific batch job.
   178→// The job is queried using the database id. The user is passed directly,
   179→// instead as part of the context.
   180→// It returns a pointer to a schema.Job data structure and an error variable.
   181→// To check if no job was found test err == sql.ErrNoRows
   182→func (r *JobRepository) FindByIDWithUser(user *schema.User, jobID int64) (*schema.Job, error) {
   183→	q := sq.Select(jobColumns...).
   184→		From("job").Where("job.id = ?", jobID)
   185→
   186→	q, qerr := SecurityCheckWithUser(user, q)
   187→	if qerr != nil {
   188→		return nil, qerr
   189→	}
   190→
   191→	return scanJob(q.RunWith(r.stmtCache).QueryRow())
   192→}
   193→
   194→// FindByIDDirect executes a SQL query to find a specific batch job.
   195→// The job is queried using the database id.
   196→// It returns a pointer to a schema.Job data structure and an error variable.
   197→// To check if no job was found test err == sql.ErrNoRows
   198→func (r *JobRepository) FindByIDDirect(jobID int64) (*schema.Job, error) {
   199→	q := sq.Select(jobColumns...).
   200→		From("job").Where("job.id = ?", jobID)
   201→	return scanJob(q.RunWith(r.stmtCache).QueryRow())
   202→}
   203→
   204→// FindByJobID executes a SQL query to find a specific batch job.
   205→// The job is queried using the slurm id and the clustername.
   206→// It returns a pointer to a schema.Job data structure and an error variable.
   207→// To check if no job was found test err == sql.ErrNoRows
   208→func (r *JobRepository) FindByJobID(ctx context.Context, jobID int64, startTime int64, cluster string) (*schema.Job, error) {
   209→	q := sq.Select(jobColumns...).
   210→		From("job").
   211→		Where("job.job_id = ?", jobID).
   212→		Where("job.cluster = ?", cluster).
   213→		Where("job.start_time = ?", startTime)
   214→
   215→	q, qerr := SecurityCheck(ctx, q)
   216→	if qerr != nil {
   217→		return nil, qerr
   218→	}
   219→
   220→	return scanJob(q.RunWith(r.stmtCache).QueryRow())
   221→}
   222→
   223→// IsJobOwner checks if the specified user owns the batch job identified by jobID,
   224→// startTime, and cluster. Returns true if the user is the owner, false otherwise.
   225→// This method does not return errors; it returns false for both non-existent jobs
   226→// and jobs owned by other users.
   227→func (r *JobRepository) IsJobOwner(jobID int64, startTime int64, user string, cluster string) bool {
   228→	q := sq.Select("id").
   229→		From("job").
   230→		Where("job.job_id = ?", jobID).
   231→		Where("job.hpc_user = ?", user).
   232→		Where("job.cluster = ?", cluster).
   233→		Where("job.start_time = ?", startTime)
   234→
   235→	_, err := scanJob(q.RunWith(r.stmtCache).QueryRow())
   236→	if err != nil && err != sql.ErrNoRows {
   237→		cclog.Warnf("IsJobOwner: unexpected error for jobID=%d, user=%s, cluster=%s: %v", jobID, user, cluster, err)
   238→	}
   239→	return err != sql.ErrNoRows
   240→}
   241→
   242→func (r *JobRepository) FindConcurrentJobs(
   243→	ctx context.Context,
   244→	job *schema.Job,
   245→) (*model.JobLinkResultList, error) {
   246→	if job == nil {
   247→		return nil, nil
   248→	}
   249→
   250→	query, qerr := SecurityCheck(ctx, sq.Select("job.id", "job.job_id", "job.start_time").From("job"))
   251→	if qerr != nil {
   252→		return nil, qerr
   253→	}
   254→
   255→	query = query.Where("cluster = ?", job.Cluster)
   256→
   257→	if len(job.Resources) == 0 {
   258→		return nil, fmt.Errorf("job has no resources defined")
   259→	}
   260→
   261→	var startTime int64
   262→	var stopTime int64
   263→
   264→	startTime = job.StartTime
   265→	hostname := job.Resources[0].Hostname
   266→
   267→	if job.State == schema.JobStateRunning {
   268→		stopTime = time.Now().Unix()
   269→	} else {
   270→		stopTime = startTime + int64(job.Duration)
   271→	}
   272→
   273→	// Time buffer constant for finding overlapping jobs
   274→	// overlapBufferEnd: 200s buffer at job end to account for scheduling/cleanup overlap
   275→	const overlapBufferEnd = 200
   276→
   277→	stopTimeTail := stopTime - overlapBufferEnd
   278→	startTimeFront := startTime + overlapBufferEnd
   279→
   280→	queryRunning := query.Where("job.job_state = ?", "running").
   281→		Where("job.start_time <= ?", stopTimeTail)
   282→	// Get At Least One Exact Hostname Match from JSON Resources Array in Database
   283→	queryRunning = queryRunning.Where("EXISTS (SELECT 1 FROM json_each(job.resources) WHERE json_extract(value, '$.hostname') = ?)", hostname)
   284→
   285→	query = query.Where("job.job_state != ?", "running").
   286→		Where("job.start_time < ?", stopTimeTail).
   287→		Where("(job.start_time + job.duration) > ?", startTimeFront)
   288→	// Get At Least One Exact Hostname Match from JSON Resources Array in Database
   289→	query = query.Where("EXISTS (SELECT 1 FROM json_each(job.resources) WHERE json_extract(value, '$.hostname') = ?)", hostname)
   290→
   291→	rows, err := query.RunWith(r.stmtCache).Query()
   292→	if err != nil {
   293→		cclog.Errorf("Error while running concurrent jobs query: %v", err)
   294→		return nil, fmt.Errorf("failed to execute concurrent jobs query: %w", err)
   295→	}
   296→	defer rows.Close()
   297→
   298→	items := make([]*model.JobLink, 0, 10)
   299→	queryString := fmt.Sprintf("cluster=%s", job.Cluster)
   300→
   301→	for rows.Next() {
   302→		var id, jobID, startTime sql.NullInt64
   303→
   304→		if err = rows.Scan(&id, &jobID, &startTime); err != nil {
   305→			cclog.Warnf("Error while scanning concurrent job rows: %v", err)
   306→			return nil, fmt.Errorf("failed to scan concurrent job row: %w", err)
   307→		}
   308→
   309→		if id.Valid {
   310→			queryString += fmt.Sprintf("&jobId=%d", int(jobID.Int64))
   311→			items = append(items,
   312→				&model.JobLink{
   313→					ID:    fmt.Sprint(id.Int64),
   314→					JobID: int(jobID.Int64),
   315→				})
   316→		}
   317→	}
   318→
   319→	rows, err = queryRunning.RunWith(r.stmtCache).Query()
   320→	if err != nil {
   321→		cclog.Errorf("Error while running concurrent running jobs query: %v", err)
   322→		return nil, fmt.Errorf("failed to execute concurrent running jobs query: %w", err)
   323→	}
   324→	defer rows.Close()
   325→
   326→	for rows.Next() {
   327→		var id, jobID, startTime sql.NullInt64
   328→
   329→		if err := rows.Scan(&id, &jobID, &startTime); err != nil {
   330→			cclog.Warnf("Error while scanning running concurrent job rows: %v", err)
   331→			return nil, fmt.Errorf("failed to scan running concurrent job row: %w", err)
   332→		}
   333→
   334→		if id.Valid {
   335→			queryString += fmt.Sprintf("&jobId=%d", int(jobID.Int64))
   336→			items = append(items,
   337→				&model.JobLink{
   338→					ID:    fmt.Sprint(id.Int64),
   339→					JobID: int(jobID.Int64),
   340→				})
   341→		}
   342→	}
   343→
   344→	cnt := len(items)
   345→
   346→	return &model.JobLinkResultList{
   347→		ListQuery: &queryString,
   348→		Items:     items,
   349→		Count:     &cnt,
   350→	}, nil
   351→}
   352→


     1→// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.
     2→// All rights reserved. This file is part of cc-backend.
     3→// Use of this source code is governed by a MIT-style
     4→// license that can be found in the LICENSE file.
     5→
     6→package repository
     7→
     8→import (
     9→	"encoding/json"
    10→	"fmt"
    11→
    12→	cclog "github.com/ClusterCockpit/cc-lib/v2/ccLogger"
    13→	"github.com/ClusterCockpit/cc-lib/v2/schema"
    14→	sq "github.com/Masterminds/squirrel"
    15→)
    16→
    17→const NamedJobCacheInsert string = `INSERT INTO job_cache (
    18→	job_id, hpc_user, project, cluster, subcluster, cluster_partition, array_job_id, num_nodes, num_hwthreads, num_acc,
    19→	shared, monitoring_status, smt, job_state, start_time, duration, walltime, footprint, energy, energy_footprint, resources, meta_data
    20→) VALUES (
    21→	:job_id, :hpc_user, :project, :cluster, :subcluster, :cluster_partition, :array_job_id, :num_nodes, :num_hwthreads, :num_acc,
    22→  :shared, :monitoring_status, :smt, :job_state, :start_time, :duration, :walltime, :footprint,  :energy, :energy_footprint, :resources, :meta_data
    23→);`
    24→
    25→const NamedJobInsert string = `INSERT INTO job (
    26→	job_id, hpc_user, project, cluster, subcluster, cluster_partition, array_job_id, num_nodes, num_hwthreads, num_acc,
    27→	shared, monitoring_status, smt, job_state, start_time, duration, walltime, footprint, energy, energy_footprint, resources, meta_data
    28→) VALUES (
    29→	:job_id, :hpc_user, :project, :cluster, :subcluster, :cluster_partition, :array_job_id, :num_nodes, :num_hwthreads, :num_acc,
    30→  :shared, :monitoring_status, :smt, :job_state, :start_time, :duration, :walltime, :footprint,  :energy, :energy_footprint, :resources, :meta_data
    31→);`
    32→
    33→// InsertJobDirect inserts a job directly into the job table (not job_cache).
    34→// Use this when the returned ID will be used for operations on the job table
    35→// (e.g., adding tags), or for imported jobs that are already completed.
    36→func (r *JobRepository) InsertJobDirect(job *schema.Job) (int64, error) {
    37→	r.Mutex.Lock()
    38→	defer r.Mutex.Unlock()
    39→
    40→	res, err := r.DB.NamedExec(NamedJobInsert, job)
    41→	if err != nil {
    42→		cclog.Warn("Error while NamedJobInsert (direct)")
    43→		return 0, err
    44→	}
    45→	id, err := res.LastInsertId()
    46→	if err != nil {
    47→		cclog.Warn("Error while getting last insert ID (direct)")
    48→		return 0, err
    49→	}
    50→
    51→	return id, nil
    52→}
    53→
    54→func (r *JobRepository) InsertJob(job *schema.Job) (int64, error) {
    55→	r.Mutex.Lock()
    56→	defer r.Mutex.Unlock()
    57→
    58→	res, err := r.DB.NamedExec(NamedJobCacheInsert, job)
    59→	if err != nil {
    60→		cclog.Warn("Error while NamedJobInsert")
    61→		return 0, err
    62→	}
    63→	id, err := res.LastInsertId()
    64→	if err != nil {
    65→		cclog.Warn("Error while getting last insert ID")
    66→		return 0, err
    67→	}
    68→
    69→	return id, nil
    70→}
    71→
    72→func (r *JobRepository) SyncJobs() ([]*schema.Job, error) {
    73→	r.Mutex.Lock()
    74→	defer r.Mutex.Unlock()
    75→
    76→	query := sq.Select(jobCacheColumns...).From("job_cache")
    77→
    78→	rows, err := query.RunWith(r.stmtCache).Query()
    79→	if err != nil {
    80→		cclog.Errorf("Error while running query %v", err)
    81→		return nil, err
    82→	}
    83→	defer rows.Close()
    84→
    85→	jobs := make([]*schema.Job, 0, 50)
    86→	for rows.Next() {
    87→		job, err := scanJob(rows)
    88→		if err != nil {
    89→			cclog.Warn("Error while scanning rows")
    90→			return nil, err
    91→		}
    92→		jobs = append(jobs, job)
    93→	}
    94→
    95→	// Use INSERT OR IGNORE to skip jobs already transferred by the stop path
    96→	_, err = r.DB.Exec(
    97→		"INSERT OR IGNORE INTO job (job_id, cluster, subcluster, start_time, hpc_user, project, cluster_partition, array_job_id, num_nodes, num_hwthreads, num_acc, shared, monitoring_status, smt, job_state, duration, walltime, footprint, energy, energy_footprint, resources, meta_data) SELECT job_id, cluster, subcluster, start_time, hpc_user, project, cluster_partition, array_job_id, num_nodes, num_hwthreads, num_acc, shared, monitoring_status, smt, job_state, duration, walltime, footprint, energy, energy_footprint, resources, meta_data FROM job_cache")
    98→	if err != nil {
    99→		cclog.Warnf("Error while Job sync: %v", err)
   100→		return nil, err
   101→	}
   102→
   103→	_, err = r.DB.Exec("DELETE FROM job_cache")
   104→	if err != nil {
   105→		cclog.Warnf("Error while Job cache clean: %v", err)
   106→		return nil, err
   107→	}
   108→
   109→	// Resolve correct job.id from the job table. The IDs read from job_cache
   110→	// are from a different auto-increment sequence and must not be used to
   111→	// query the job table.
   112→	for _, job := range jobs {
   113→		var newID int64
   114→		if err := sq.Select("job.id").From("job").
   115→			Where("job.job_id = ? AND job.cluster = ? AND job.start_time = ?",
   116→				job.JobID, job.Cluster, job.StartTime).
   117→			RunWith(r.stmtCache).QueryRow().Scan(&newID); err != nil {
   118→			cclog.Warnf("SyncJobs: could not resolve job table id for job %d on %s: %v",
   119→				job.JobID, job.Cluster, err)
   120→			continue
   121→		}
   122→		job.ID = &newID
   123→	}
   124→
   125→	return jobs, nil
   126→}
   127→
   128→// TransferCachedJobToMain moves a job from job_cache to the job table.
   129→// Caller must hold r.Mutex. Returns the new job table ID.
   130→func (r *JobRepository) TransferCachedJobToMain(cacheID int64) (int64, error) {
   131→	res, err := r.DB.Exec(
   132→		"INSERT INTO job (job_id, cluster, subcluster, start_time, hpc_user, project, cluster_partition, array_job_id, num_nodes, num_hwthreads, num_acc, shared, monitoring_status, smt, job_state, duration, walltime, footprint, energy, energy_footprint, resources, meta_data) SELECT job_id, cluster, subcluster, start_time, hpc_user, project, cluster_partition, array_job_id, num_nodes, num_hwthreads, num_acc, shared, monitoring_status, smt, job_state, duration, walltime, footprint, energy, energy_footprint, resources, meta_data FROM job_cache WHERE id = ?",
   133→		cacheID)
   134→	if err != nil {
   135→		return 0, fmt.Errorf("transferring cached job %d to main table failed: %w", cacheID, err)
   136→	}
   137→
   138→	newID, err := res.LastInsertId()
   139→	if err != nil {
   140→		return 0, fmt.Errorf("getting new job ID after transfer failed: %w", err)
   141→	}
   142→
   143→	_, err = r.DB.Exec("DELETE FROM job_cache WHERE id = ?", cacheID)
   144→	if err != nil {
   145→		return 0, fmt.Errorf("deleting cached job %d after transfer failed: %w", cacheID, err)
   146→	}
   147→
   148→	return newID, nil
   149→}
   150→
   151→// Start inserts a new job in the table, returning the unique job ID.
   152→// Statistics are not transfered!
   153→func (r *JobRepository) Start(job *schema.Job) (id int64, err error) {
   154→	job.RawFootprint, err = json.Marshal(job.Footprint)
   155→	if err != nil {
   156→		return -1, fmt.Errorf("REPOSITORY/JOB > encoding footprint field failed: %w", err)
   157→	}
   158→
   159→	job.RawResources, err = json.Marshal(job.Resources)
   160→	if err != nil {
   161→		return -1, fmt.Errorf("REPOSITORY/JOB > encoding resources field failed: %w", err)
   162→	}
   163→
   164→	job.RawMetaData, err = json.Marshal(job.MetaData)
   165→	if err != nil {
   166→		return -1, fmt.Errorf("REPOSITORY/JOB > encoding metaData field failed: %w", err)
   167→	}
   168→
   169→	return r.InsertJob(job)
   170→}
   171→
   172→// StartDirect inserts a new job directly into the job table (not job_cache).
   173→// Use this when the returned ID will immediately be used for job table
   174→// operations such as adding tags.
   175→func (r *JobRepository) StartDirect(job *schema.Job) (id int64, err error) {
   176→	job.RawFootprint, err = json.Marshal(job.Footprint)
   177→	if err != nil {
   178→		return -1, fmt.Errorf("REPOSITORY/JOB > encoding footprint field failed: %w", err)
   179→	}
   180→
   181→	job.RawResources, err = json.Marshal(job.Resources)
   182→	if err != nil {
   183→		return -1, fmt.Errorf("REPOSITORY/JOB > encoding resources field failed: %w", err)
   184→	}
   185→
   186→	job.RawMetaData, err = json.Marshal(job.MetaData)
   187→	if err != nil {
   188→		return -1, fmt.Errorf("REPOSITORY/JOB > encoding metaData field failed: %w", err)
   189→	}
   190→
   191→	return r.InsertJobDirect(job)
   192→}
   193→
   194→// Stop updates the job with the database id jobId using the provided arguments.
   195→func (r *JobRepository) Stop(
   196→	jobID int64,
   197→	duration int32,
   198→	state schema.JobState,
   199→	monitoringStatus int32,
   200→) (err error) {
   201→	// Invalidate cache entries as job state is changing
   202→	r.cache.Del(fmt.Sprintf("metadata:%d", jobID))
   203→	r.cache.Del(fmt.Sprintf("energyFootprint:%d", jobID))
   204→
   205→	stmt := sq.Update("job").
   206→		Set("job_state", state).
   207→		Set("duration", duration).
   208→		Set("monitoring_status", monitoringStatus).
   209→		Where("job.id = ?", jobID)
   210→
   211→	_, err = stmt.RunWith(r.stmtCache).Exec()
   212→	return err
   213→}
   214→
   215→


<persisted-output>
Output too large (49.5KB). Full output saved to: /Users/jan/.claude/projects/-Users-jan-prg-CC-cc-backend/28147033-ddc8-4056-b064-e0558fbc614e/tool-results/toolu_01WrwQfJuYuXUERAZixdLw5c.txt

Preview (first 2KB):
     1→// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.
     2→// All rights reserved. This file is part of cc-backend.
     3→// Use of this source code is governed by a MIT-style
     4→// license that can be found in the LICENSE file.
     5→
     6→// Package repository provides the data access layer for cc-backend using the repository pattern.
     7→//
     8→// The repository pattern abstracts database operations and provides a clean interface for
     9→// data access. Each major entity (Job, User, Node, Tag) has its own repository with CRUD
    10→// operations and specialized queries.
    11→//
    12→// # Database Connection
    13→//
    14→// Initialize the database connection before using any repository:
    15→//
    16→//	repository.Connect("sqlite3", "./var/job.db")
    17→//
    18→// # Configuration
    19→//
    20→// Optional: Configure repository settings before initialization:
    21→//
    22→//	repository.SetConfig(&repository.RepositoryConfig{
    23→//	    CacheSize: 2 * 1024 * 1024,     // 2MB cache
    24→//	    MaxOpenConnections: 8,           // Connection pool size
    25→//	    MinRunningJobDuration: 300,      // Filter threshold
    26→//	})
    27→//
    28→// If not configured, sensible defaults are used automatically.
    29→//
    30→// # Repositories
    31→//
    32→//   - JobRepository: Job lifecycle management and querying
    33→//   - UserRepository: User management and authentication
    34→//   - NodeRepository: Cluster node state tracking
    35→//   - Tags: Job tagging and categorization
    36→//
    37→// # Caching
    38→//
    39→// Repositories use LRU caching to improve performance. Cache keys are constructed
    40→// as "type:id" (e.g., "metadata:123"). Cache is automatically invalidated on
    41→// mutations to maintain consistency.
    42→//
    43→// # Transaction Support
    44→//
    45→// For batch operations, use transactions:
    46→//
    47→//	t, err := jobRepo.TransactionInit()
...
</persisted-output>


     1→// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.
     2→// All rights reserved. This file is part of cc-backend.
     3→// Use of this source code is governed by a MIT-style
     4→// license that can be found in the LICENSE file.
     5→
     6→// Package repository provides job query functionality with filtering, pagination,
     7→// and security controls. This file contains the main query builders and security
     8→// checks for job retrieval operations.
     9→package repository
    10→
    11→import (
    12→	"context"
    13→	"errors"
    14→	"fmt"
    15→	"regexp"
    16→	"strings"
    17→	"time"
    18→
    19→	"github.com/ClusterCockpit/cc-backend/internal/config"
    20→	"github.com/ClusterCockpit/cc-backend/internal/graph/model"
    21→	cclog "github.com/ClusterCockpit/cc-lib/v2/ccLogger"
    22→	"github.com/ClusterCockpit/cc-lib/v2/schema"
    23→	sq "github.com/Masterminds/squirrel"
    24→)
    25→
    26→const (
    27→	// Default initial capacity for job result slices
    28→	defaultJobsCapacity = 50
    29→)
    30→
    31→// QueryJobs retrieves jobs from the database with optional filtering, pagination,
    32→// and sorting. Security controls are automatically applied based on the user context.
    33→//
    34→// Parameters:
    35→//   - ctx: Context containing user authentication information
    36→//   - filters: Optional job filters (cluster, state, user, time ranges, etc.)
    37→//   - page: Optional pagination parameters (page number and items per page)
    38→//   - order: Optional sorting specification (column or footprint field)
    39→//
    40→// Returns a slice of jobs matching the criteria, or an error if the query fails.
    41→// The function enforces role-based access control through SecurityCheck.
    42→func (r *JobRepository) QueryJobs(
    43→	ctx context.Context,
    44→	filters []*model.JobFilter,
    45→	page *model.PageRequest,
    46→	order *model.OrderByInput,
    47→) ([]*schema.Job, error) {
    48→	query, qerr := SecurityCheck(ctx, sq.Select(jobColumns...).From("job"))
    49→	if qerr != nil {
    50→		return nil, qerr
    51→	}
    52→
    53→	if order != nil {
    54→		field := toSnakeCase(order.Field)
    55→		if order.Type == "col" {
    56→			switch order.Order {
    57→			case model.SortDirectionEnumAsc:
    58→				query = query.OrderBy(fmt.Sprintf("job.%s ASC", field))
    59→			case model.SortDirectionEnumDesc:
    60→				query = query.OrderBy(fmt.Sprintf("job.%s DESC", field))
    61→			default:
    62→				return nil, errors.New("invalid sorting order for column")
    63→			}
    64→		} else {
    65→			// Order by footprint JSON field values
    66→			query = query.Where("JSON_VALID(meta_data)")
    67→			switch order.Order {
    68→			case model.SortDirectionEnumAsc:
    69→				query = query.OrderBy(fmt.Sprintf("JSON_EXTRACT(footprint, \"$.%s\") ASC", field))
    70→			case model.SortDirectionEnumDesc:
    71→				query = query.OrderBy(fmt.Sprintf("JSON_EXTRACT(footprint, \"$.%s\") DESC", field))
    72→			default:
    73→				return nil, errors.New("invalid sorting order for footprint")
    74→			}
    75→		}
    76→	}
    77→
    78→	if page != nil && page.ItemsPerPage != -1 {
    79→		limit := uint64(page.ItemsPerPage)
    80→		query = query.Offset((uint64(page.Page) - 1) * limit).Limit(limit)
    81→	}
    82→
    83→	for _, f := range filters {
    84→		query = BuildWhereClause(f, query)
    85→	}
    86→
    87→	rows, err := query.RunWith(r.stmtCache).Query()
    88→	if err != nil {
    89→		queryString, queryVars, _ := query.ToSql()
    90→		return nil, fmt.Errorf("query failed [%s] %v: %w", queryString, queryVars, err)
    91→	}
    92→	defer rows.Close()
    93→
    94→	jobs := make([]*schema.Job, 0, defaultJobsCapacity)
    95→	for rows.Next() {
    96→		job, err := scanJob(rows)
    97→		if err != nil {
    98→			cclog.Warnf("Error scanning job row: %v", err)
    99→			return nil, fmt.Errorf("failed to scan job row: %w", err)
   100→		}
   101→		jobs = append(jobs, job)
   102→	}
   103→
   104→	if err := rows.Err(); err != nil {
   105→		return nil, fmt.Errorf("error iterating job rows: %w", err)
   106→	}
   107→
   108→	return jobs, nil
   109→}
   110→
   111→// CountJobs returns the total number of jobs matching the given filters.
   112→// Security controls are automatically applied based on the user context.
   113→// Uses DISTINCT count to handle tag filters correctly (jobs may appear multiple
   114→// times when joined with the tag table).
   115→func (r *JobRepository) CountJobs(
   116→	ctx context.Context,
   117→	filters []*model.JobFilter,
   118→) (int, error) {
   119→	query, qerr := SecurityCheck(ctx, sq.Select("count(DISTINCT job.id)").From("job"))
   120→	if qerr != nil {
   121→		return 0, qerr
   122→	}
   123→
   124→	for _, f := range filters {
   125→		query = BuildWhereClause(f, query)
   126→	}
   127→
   128→	var count int
   129→	if err := query.RunWith(r.DB).Scan(&count); err != nil {
   130→		return 0, fmt.Errorf("failed to count jobs: %w", err)
   131→	}
   132→
   133→	return count, nil
   134→}
   135→
   136→// SecurityCheckWithUser applies role-based access control filters to a job query
   137→// based on the provided user's roles and permissions.
   138→//
   139→// Access rules by role:
   140→//   - API role (exclusive): Full access to all jobs
   141→//   - Admin/Support roles: Full access to all jobs
   142→//   - Manager role: Access to jobs in managed projects plus own jobs
   143→//   - User role: Access only to own jobs
   144→//
   145→// Returns an error if the user is nil or has no recognized roles.
   146→func SecurityCheckWithUser(user *schema.User, query sq.SelectBuilder) (sq.SelectBuilder, error) {
   147→	if user == nil {
   148→		var qnil sq.SelectBuilder
   149→		return qnil, fmt.Errorf("user context is nil")
   150→	}
   151→
   152→	switch {
   153→	case len(user.Roles) == 1 && user.HasRole(schema.RoleAPI):
   154→		return query, nil
   155→	case user.HasAnyRole([]schema.Role{schema.RoleAdmin, schema.RoleSupport}):
   156→		return query, nil
   157→	case user.HasRole(schema.RoleManager):
   158→		if len(user.Projects) != 0 {
   159→			return query.Where(sq.Or{sq.Eq{"job.project": user.Projects}, sq.Eq{"job.hpc_user": user.Username}}), nil
   160→		}
   161→		cclog.Debugf("Manager '%s' has no assigned projects, restricting to personal jobs", user.Username)
   162→		return query.Where("job.hpc_user = ?", user.Username), nil
   163→	case user.HasRole(schema.RoleUser):
   164→		return query.Where("job.hpc_user = ?", user.Username), nil
   165→	default:
   166→		var qnil sq.SelectBuilder
   167→		return qnil, fmt.Errorf("user has no or unknown roles")
   168→	}
   169→}
   170→
   171→// SecurityCheck extracts the user from the context and applies role-based access
   172→// control filters to the query. This is a convenience wrapper around SecurityCheckWithUser.
   173→func SecurityCheck(ctx context.Context, query sq.SelectBuilder) (sq.SelectBuilder, error) {
   174→	user := GetUserFromContext(ctx)
   175→	return SecurityCheckWithUser(user, query)
   176→}
   177→
   178→// BuildWhereClause constructs SQL WHERE conditions from a JobFilter and applies
   179→// them to the query. Supports filtering by job properties (cluster, state, user),
   180→// time ranges, resource usage, tags, and JSON field searches in meta_data,
   181→// footprint, and resources columns.
   182→func BuildWhereClause(filter *model.JobFilter, query sq.SelectBuilder) sq.SelectBuilder {
   183→	// Primary Key
   184→	if filter.DbID != nil {
   185→		dbIDs := make([]string, len(filter.DbID))
   186→		copy(dbIDs, filter.DbID)
   187→		query = query.Where(sq.Eq{"job.id": dbIDs})
   188→	}
   189→	// Explicit indices
   190→	if filter.Cluster != nil {
   191→		query = buildStringCondition("job.cluster", filter.Cluster, query)
   192→	}
   193→	if filter.SubCluster != nil {
   194→		query = buildStringCondition("job.subcluster", filter.SubCluster, query)
   195→	}
   196→	if filter.Partition != nil {
   197→		query = buildStringCondition("job.cluster_partition", filter.Partition, query)
   198→	}
   199→	if filter.State != nil {
   200→		states := make([]string, len(filter.State))
   201→		for i, val := range filter.State {
   202→			states[i] = string(val)
   203→		}
   204→		query = query.Where(sq.Eq{"job.job_state": states})
   205→	}
   206→	if filter.Shared != nil {
   207→		query = query.Where("job.shared = ?", *filter.Shared)
   208→	}
   209→	if filter.Project != nil {
   210→		query = buildStringCondition("job.project", filter.Project, query)
   211→	}
   212→	if filter.User != nil {
   213→		query = buildStringCondition("job.hpc_user", filter.User, query)
   214→	}
   215→	if filter.NumNodes != nil {
   216→		query = buildIntCondition("job.num_nodes", filter.NumNodes, query)
   217→	}
   218→	if filter.NumAccelerators != nil {
   219→		query = buildIntCondition("job.num_acc", filter.NumAccelerators, query)
   220→	}
   221→	if filter.NumHWThreads != nil {
   222→		query = buildIntCondition("job.num_hwthreads", filter.NumHWThreads, query)
   223→	}
   224→	if filter.ArrayJobID != nil {
   225→		query = query.Where("job.array_job_id = ?", *filter.ArrayJobID)
   226→	}
   227→	if filter.StartTime != nil {
   228→		query = buildTimeCondition("job.start_time", filter.StartTime, query)
   229→	}
   230→	if filter.Duration != nil {
   231→		query = buildIntCondition("job.duration", filter.Duration, query)
   232→	}
   233→	if filter.Energy != nil {
   234→		query = buildFloatCondition("job.energy", filter.Energy, query)
   235→	}
   236→	// Indices on Tag Table
   237→	if filter.Tags != nil {
   238→		// This is an OR-Logic query: Returns all distinct jobs with at least one of the requested tags; TODO: AND-Logic query?
   239→		query = query.Join("jobtag ON jobtag.job_id = job.id").Where(sq.Eq{"jobtag.tag_id": filter.Tags}).Distinct()
   240→	}
   241→	// No explicit Indices
   242→	if filter.JobID != nil {
   243→		query = buildStringCondition("job.job_id", filter.JobID, query)
   244→	}
   245→	// Queries Within JSONs
   246→	if filter.MetricStats != nil {
   247→		for _, ms := range filter.MetricStats {
   248→			query = buildFloatJSONCondition(ms.MetricName, ms.Range, query)
   249→		}
   250→	}
   251→	if filter.Node != nil {
   252→		query = buildResourceJSONCondition("hostname", filter.Node, query)
   253→	}
   254→	if filter.JobName != nil {
   255→		query = buildMetaJSONCondition("jobName", filter.JobName, query)
   256→	}
   257→	if filter.Schedule != nil {
   258→		interactiveJobname := "interactive"
   259→		switch *filter.Schedule {
   260→		case "interactive":
   261→			iFilter := model.StringInput{Eq: &interactiveJobname}
   262→			query = buildMetaJSONCondition("jobName", &iFilter, query)
   263→		case "batch":
   264→			sFilter := model.StringInput{Neq: &interactiveJobname}
   265→			query = buildMetaJSONCondition("jobName", &sFilter, query)
   266→		}
   267→	}
   268→
   269→	// Configurable Filter to exclude recently started jobs, see config.go: ShortRunningJobsDuration
   270→	if filter.MinRunningFor != nil {
   271→		now := time.Now().Unix()
   272→		// Only jobs whose start timestamp is more than MinRunningFor seconds in the past
   273→		// If a job completed within the configured timeframe, it will still show up after the start_time matches the condition!
   274→		query = query.Where(sq.Lt{"job.start_time": (now - int64(*filter.MinRunningFor))})
   275→	}
   276→	return query
   277→}
   278→
   279→// buildIntCondition creates a BETWEEN clause for integer range filters.
   280→// Reminder: BETWEEN Queries are slower and dont use indices as frequently: Only use if both conditions required
   281→func buildIntCondition(field string, cond *config.IntRange, query sq.SelectBuilder) sq.SelectBuilder {
   282→	if cond.From != 0 && cond.To != 0 {
   283→		return query.Where(field+" BETWEEN ? AND ?", cond.From, cond.To)
   284→	} else if cond.From != 0 {
   285→		return query.Where(field+" >= ?", cond.From)
   286→	} else if cond.To != 0 {
   287→		return query.Where(field+" <= ?", cond.To)
   288→	} else {
   289→		return query
   290→	}
   291→}
   292→
   293→// buildFloatCondition creates a BETWEEN clause for float range filters.
   294→// Reminder: BETWEEN Queries are slower and dont use indices as frequently: Only use if both conditions required
   295→func buildFloatCondition(field string, cond *model.FloatRange, query sq.SelectBuilder) sq.SelectBuilder {
   296→	if cond.From != 0.0 && cond.To != 0.0 {
   297→		return query.Where(field+" BETWEEN ? AND ?", cond.From, cond.To)
   298→	} else if cond.From != 0.0 {
   299→		return query.Where(field+" >= ?", cond.From)
   300→	} else if cond.To != 0.0 {
   301→		return query.Where(field+" <= ?", cond.To)
   302→	} else {
   303→		return query
   304→	}
   305→}
   306→
   307→// buildTimeCondition creates time range filters supporting absolute timestamps,
   308→// relative time ranges (last6h, last24h, last7d, last30d), or open-ended ranges.
   309→// Reminder: BETWEEN Queries are slower and dont use indices as frequently: Only use if both conditions required
   310→func buildTimeCondition(field string, cond *config.TimeRange, query sq.SelectBuilder) sq.SelectBuilder {
   311→	if cond.From != nil && cond.To != nil {
   312→		return query.Where(field+" BETWEEN ? AND ?", cond.From.Unix(), cond.To.Unix())
   313→	} else if cond.From != nil {
   314→		return query.Where(field+" >= ?", cond.From.Unix())
   315→	} else if cond.To != nil {
   316→		return query.Where(field+" <= ?", cond.To.Unix())
   317→	} else if cond.Range != "" {
   318→		now := time.Now().Unix()
   319→		var then int64
   320→		switch cond.Range {
   321→		case "last6h":
   322→			then = now - (60 * 60 * 6)
   323→		case "last24h":
   324→			then = now - (60 * 60 * 24)
   325→		case "last7d":
   326→			then = now - (60 * 60 * 24 * 7)
   327→		case "last30d":
   328→			then = now - (60 * 60 * 24 * 30)
   329→		default:
   330→			cclog.Debugf("No known named timeRange: startTime.range = %s", cond.Range)
   331→			return query
   332→		}
   333→		return query.Where(field+" >= ?", then)
   334→	} else {
   335→		return query
   336→	}
   337→}
   338→
   339→// buildFloatJSONCondition creates a filter on a numeric field within the footprint JSON column.
   340→// Reminder: BETWEEN Queries are slower and dont use indices as frequently: Only use if both conditions required
   341→func buildFloatJSONCondition(condName string, condRange *model.FloatRange, query sq.SelectBuilder) sq.SelectBuilder {
   342→	query = query.Where("JSON_VALID(footprint)")
   343→	if condRange.From != 0.0 && condRange.To != 0.0 {
   344→		return query.Where("JSON_EXTRACT(footprint, \"$."+condName+"\") BETWEEN ? AND ?", condRange.From, condRange.To)
   345→	} else if condRange.From != 0.0 {
   346→		return query.Where("JSON_EXTRACT(footprint, \"$."+condName+"\") >= ?", condRange.From)
   347→	} else if condRange.To != 0.0 {
   348→		return query.Where("JSON_EXTRACT(footprint, \"$."+condName+"\") <= ?", condRange.To)
   349→	} else {
   350→		return query
   351→	}
   352→}
   353→
   354→// buildStringCondition creates filters for string fields supporting equality,
   355→// inequality, prefix, suffix, substring, and IN list matching.
   356→func buildStringCondition(field string, cond *model.StringInput, query sq.SelectBuilder) sq.SelectBuilder {
   357→	if cond.Eq != nil {
   358→		return query.Where(field+" = ?", *cond.Eq)
   359→	}
   360→	if cond.Neq != nil {
   361→		return query.Where(field+" != ?", *cond.Neq)
   362→	}
   363→	if cond.StartsWith != nil {
   364→		return query.Where(field+" LIKE ?", fmt.Sprint(*cond.StartsWith, "%"))
   365→	}
   366→	if cond.EndsWith != nil {
   367→		return query.Where(field+" LIKE ?", fmt.Sprint("%", *cond.EndsWith))
   368→	}
   369→	if cond.Contains != nil {
   370→		return query.Where(field+" LIKE ?", fmt.Sprint("%", *cond.Contains, "%"))
   371→	}
   372→	if cond.In != nil {
   373→		queryElements := make([]string, len(cond.In))
   374→		copy(queryElements, cond.In)
   375→		return query.Where(sq.Or{sq.Eq{field: queryElements}})
   376→	}
   377→	return query
   378→}
   379→
   380→// buildMetaJSONCondition creates filters on fields within the meta_data JSON column.
   381→func buildMetaJSONCondition(jsonField string, cond *model.StringInput, query sq.SelectBuilder) sq.SelectBuilder {
   382→	query = query.Where("JSON_VALID(meta_data)")
   383→	if cond.Eq != nil {
   384→		return query.Where("JSON_EXTRACT(meta_data, \"$."+jsonField+"\") = ?", *cond.Eq)
   385→	}
   386→	if cond.Neq != nil {
   387→		return query.Where("JSON_EXTRACT(meta_data, \"$."+jsonField+"\") != ?", *cond.Neq)
   388→	}
   389→	if cond.StartsWith != nil {
   390→		return query.Where("JSON_EXTRACT(meta_data, \"$."+jsonField+"\") LIKE ?", fmt.Sprint(*cond.StartsWith, "%"))
   391→	}
   392→	if cond.EndsWith != nil {
   393→		return query.Where("JSON_EXTRACT(meta_data, \"$."+jsonField+"\") LIKE ?", fmt.Sprint("%", *cond.EndsWith))
   394→	}
   395→	if cond.Contains != nil {
   396→		return query.Where("JSON_EXTRACT(meta_data, \"$."+jsonField+"\") LIKE ?", fmt.Sprint("%", *cond.Contains, "%"))
   397→	}
   398→	return query
   399→}
   400→
   401→// buildResourceJSONCondition creates filters on fields within the resources JSON array column.
   402→// Uses json_each to search within array elements.
   403→func buildResourceJSONCondition(jsonField string, cond *model.StringInput, query sq.SelectBuilder) sq.SelectBuilder {
   404→	query = query.Where("JSON_VALID(resources)")
   405→	if cond.Eq != nil {
   406→		return query.Where("EXISTS (SELECT 1 FROM json_each(job.resources) WHERE json_extract(value, \"$."+jsonField+"\") = ?)", *cond.Eq)
   407→	}
   408→	if cond.Neq != nil { // Currently Unused
   409→		return query.Where("EXISTS (SELECT 1 FROM json_each(job.resources) WHERE json_extract(value, \"$."+jsonField+"\") != ?)", *cond.Neq)
   410→	}
   411→	if cond.StartsWith != nil { // Currently Unused
   412→		return query.Where("EXISTS (SELECT 1 FROM json_each(job.resources) WHERE json_extract(value, \"$."+jsonField+"\")) LIKE ?)", fmt.Sprint(*cond.StartsWith, "%"))
   413→	}
   414→	if cond.EndsWith != nil { // Currently Unused
   415→		return query.Where("EXISTS (SELECT 1 FROM json_each(job.resources) WHERE json_extract(value, \"$."+jsonField+"\") LIKE ?)", fmt.Sprint("%", *cond.EndsWith))
   416→	}
   417→	if cond.Contains != nil {
   418→		return query.Where("EXISTS (SELECT 1 FROM json_each(job.resources) WHERE json_extract(value, \"$."+jsonField+"\") LIKE ?)", fmt.Sprint("%", *cond.Contains, "%"))
   419→	}
   420→	return query
   421→}
   422→
   423→var (
   424→	matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
   425→	matchAllCap   = regexp.MustCompile("([a-z0-9])([A-Z])")
   426→)
   427→
   428→// toSnakeCase converts camelCase strings to snake_case for SQL column names.
   429→// Includes security checks to prevent SQL injection attempts.
   430→// Panics if potentially dangerous characters are detected.
   431→func toSnakeCase(str string) string {
   432→	for _, c := range str {
   433→		if c == '\'' || c == '\\' || c == '"' || c == ';' || c == '-' || c == ' ' {
   434→			cclog.Panicf("toSnakeCase: potentially dangerous character detected in input: %q", str)
   435→		}
   436→	}
   437→
   438→	snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
   439→	snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
   440→	return strings.ToLower(snake)
   441→}
   442→


     1→// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.
     2→// All rights reserved. This file is part of cc-backend.
     3→// Use of this source code is governed by a MIT-style
     4→// license that can be found in the LICENSE file.
     5→
     6→// This file contains job statistics and histogram generation functionality for the JobRepository.
     7→//
     8→// # Job Statistics
     9→//
    10→// The statistics methods provide aggregated metrics about jobs including total jobs, users,
    11→// walltime, and resource usage (nodes, cores, accelerators). Statistics can be computed:
    12→//   - Overall (JobsStats): Single aggregate across all matching jobs
    13→//   - Grouped (JobsStatsGrouped): Aggregated by user, project, cluster, or subcluster
    14→//   - Counts (JobCountGrouped, AddJobCount): Simple job counts with optional filtering
    15→//
    16→// All statistics methods support filtering via JobFilter and respect security contexts.
    17→//
    18→// # Histograms
    19→//
    20→// Histogram methods generate distribution data for visualization:
    21→//   - Duration, nodes, cores, accelerators (AddHistograms)
    22→//   - Job metrics like CPU load, memory usage (AddMetricHistograms)
    23→//
    24→// Histograms use intelligent binning:
    25→//   - Duration: Variable bin sizes (1m, 10m, 1h, 6h, 12h, 24h) with zero-padding
    26→//   - Resources: Natural value-based bins
    27→//   - Metrics: Normalized to peak values with configurable bin counts
    28→//
    29→// # Running vs. Completed Jobs
    30→//
    31→// Statistics handle running jobs specially:
    32→//   - Duration calculated as (now - start_time) for running jobs
    33→//   - Metric histograms for running jobs load data from metric backend instead of footprint
    34→//   - Job state filtering distinguishes running/completed jobs
    35→//
    36→// # Performance Considerations
    37→//
    38→// - All queries use prepared statements via stmtCache
    39→// - Complex aggregations use SQL for efficiency
    40→// - Histogram pre-initialization ensures consistent bin ranges
    41→// - Metric histogram queries limited to 5000 jobs for running job analysis
    42→
    43→package repository
    44→
    45→import (
    46→	"context"
    47→	"database/sql"
    48→	"fmt"
    49→	"time"
    50→
    51→	"github.com/ClusterCockpit/cc-backend/internal/config"
    52→	"github.com/ClusterCockpit/cc-backend/internal/graph/model"
    53→	"github.com/ClusterCockpit/cc-backend/internal/metricdispatch"
    54→	"github.com/ClusterCockpit/cc-backend/pkg/archive"
    55→	cclog "github.com/ClusterCockpit/cc-lib/v2/ccLogger"
    56→	"github.com/ClusterCockpit/cc-lib/v2/schema"
    57→	sq "github.com/Masterminds/squirrel"
    58→)
    59→
    60→// groupBy2column maps GraphQL Aggregate enum values to their corresponding database column names.
    61→// Used by JobsStatsGrouped and JobCountGrouped to translate user-facing grouping dimensions
    62→// into SQL GROUP BY clauses. GraphQL validation ensures only valid enum values are accepted.
    63→var groupBy2column = map[model.Aggregate]string{
    64→	model.AggregateUser:       "job.hpc_user",
    65→	model.AggregateProject:    "job.project",
    66→	model.AggregateCluster:    "job.cluster",
    67→	model.AggregateSubcluster: "job.subcluster",
    68→}
    69→
    70→// sortBy2column maps GraphQL SortByAggregate enum values to their corresponding computed column names.
    71→// Used by JobsStatsGrouped to translate sort preferences into SQL ORDER BY clauses.
    72→// Column names match the AS aliases used in buildStatsQuery.
    73→var sortBy2column = map[model.SortByAggregate]string{
    74→	model.SortByAggregateTotaljobs:      "totalJobs",
    75→	model.SortByAggregateTotalusers:     "totalUsers",
    76→	model.SortByAggregateTotalwalltime:  "totalWalltime",
    77→	model.SortByAggregateTotalnodes:     "totalNodes",
    78→	model.SortByAggregateTotalnodehours: "totalNodeHours",
    79→	model.SortByAggregateTotalcores:     "totalCores",
    80→	model.SortByAggregateTotalcorehours: "totalCoreHours",
    81→	model.SortByAggregateTotalaccs:      "totalAccs",
    82→	model.SortByAggregateTotalacchours:  "totalAccHours",
    83→}
    84→
    85→// buildCountQuery constructs a SQL query to count jobs with optional grouping and filtering.
    86→//
    87→// Parameters:
    88→//   - filter: Job filters to apply (cluster, user, time range, etc.)
    89→//   - kind: Special filter - "running" for running jobs only, "short" for jobs under threshold
    90→//   - col: Column name to GROUP BY; empty string for total count without grouping
    91→//
    92→// Returns a SelectBuilder that produces either:
    93→//   - Single count: COUNT(job.id) when col is empty
    94→//   - Grouped counts: col, COUNT(job.id) when col is specified
    95→//
    96→// The kind parameter enables counting specific job categories:
    97→//   - "running": Only jobs with job_state = 'running'
    98→//   - "short": Only jobs with duration < ShortRunningJobsDuration config value
    99→//   - empty: All jobs matching filters
   100→func (r *JobRepository) buildCountQuery(
   101→	filter []*model.JobFilter,
   102→	kind string,
   103→	col string,
   104→) sq.SelectBuilder {
   105→	var query sq.SelectBuilder
   106→
   107→	if col != "" {
   108→		query = sq.Select(col, "COUNT(job.id)").From("job").GroupBy(col)
   109→	} else {
   110→		query = sq.Select("COUNT(job.id)").From("job")
   111→	}
   112→
   113→	switch kind {
   114→	case "running":
   115→		query = query.Where("job.job_state = ?", "running")
   116→	case "short":
   117→		query = query.Where("job.duration < ?", config.Keys.ShortRunningJobsDuration)
   118→	}
   119→
   120→	for _, f := range filter {
   121→		query = BuildWhereClause(f, query)
   122→	}
   123→
   124→	return query
   125→}
   126→
   127→// buildStatsQuery constructs a SQL query to compute comprehensive job statistics with optional grouping.
   128→//
   129→// Parameters:
   130→//   - filter: Job filters to apply (cluster, user, time range, etc.)
   131→//   - col: Column name to GROUP BY; empty string for overall statistics without grouping
   132→//
   133→// Returns a SelectBuilder that produces comprehensive statistics:
   134→//   - totalJobs: Count of jobs
   135→//   - totalUsers: Count of distinct users (always 0 when grouping by user)
   136→//   - totalWalltime: Sum of job durations in hours
   137→//   - totalNodes: Sum of nodes used across all jobs
   138→//   - totalNodeHours: Sum of (duration × num_nodes) in hours
   139→//   - totalCores: Sum of hardware threads used across all jobs
   140→//   - totalCoreHours: Sum of (duration × num_hwthreads) in hours
   141→//   - totalAccs: Sum of accelerators used across all jobs
   142→//   - totalAccHours: Sum of (duration × num_acc) in hours
   143→//
   144→// Special handling:
   145→//   - Running jobs: Duration calculated as (now - start_time) instead of stored duration
   146→//   - Grouped queries: Also select grouping column and user's display name from hpc_user table
   147→//   - All time values converted from seconds to hours (÷ 3600) and rounded
   148→func (r *JobRepository) buildStatsQuery(
   149→	filter []*model.JobFilter,
   150→	col string,
   151→) sq.SelectBuilder {
   152→	var query sq.SelectBuilder
   153→
   154→	if col != "" {
   155→		query = sq.Select(
   156→			col,
   157→			"name",
   158→			"COUNT(job.id) as totalJobs",
   159→			"COUNT(DISTINCT job.hpc_user) AS totalUsers",
   160→			fmt.Sprintf(`CAST(ROUND(SUM((CASE WHEN job.job_state = "running" THEN %d - job.start_time ELSE job.duration END)) / 3600) as int) as totalWalltime`, time.Now().Unix()),
   161→			`CAST(SUM(job.num_nodes) as int) as totalNodes`,
   162→			fmt.Sprintf(`CAST(ROUND(SUM((CASE WHEN job.job_state = "running" THEN %d - job.start_time ELSE job.duration END) * job.num_nodes) / 3600) as int) as totalNodeHours`, time.Now().Unix()),
   163→			`CAST(SUM(job.num_hwthreads) as int) as totalCores`,
   164→			fmt.Sprintf(`CAST(ROUND(SUM((CASE WHEN job.job_state = "running" THEN %d - job.start_time ELSE job.duration END) * job.num_hwthreads) / 3600) as int) as totalCoreHours`, time.Now().Unix()),
   165→			`CAST(SUM(job.num_acc) as int) as totalAccs`,
   166→			fmt.Sprintf(`CAST(ROUND(SUM((CASE WHEN job.job_state = "running" THEN %d - job.start_time ELSE job.duration END) * job.num_acc) / 3600) as int) as totalAccHours`, time.Now().Unix()),
   167→		).From("job").LeftJoin("hpc_user ON hpc_user.username = job.hpc_user").GroupBy(col)
   168→	} else {
   169→		query = sq.Select(
   170→			"COUNT(job.id) as totalJobs",
   171→			"COUNT(DISTINCT job.hpc_user) AS totalUsers",
   172→			fmt.Sprintf(`CAST(ROUND(SUM((CASE WHEN job.job_state = "running" THEN %d - job.start_time ELSE job.duration END)) / 3600) as int)`, time.Now().Unix()),
   173→			`CAST(SUM(job.num_nodes) as int)`,
   174→			fmt.Sprintf(`CAST(ROUND(SUM((CASE WHEN job.job_state = "running" THEN %d - job.start_time ELSE job.duration END) * job.num_nodes) / 3600) as int)`, time.Now().Unix()),
   175→			`CAST(SUM(job.num_hwthreads) as int)`,
   176→			fmt.Sprintf(`CAST(ROUND(SUM((CASE WHEN job.job_state = "running" THEN %d - job.start_time ELSE job.duration END) * job.num_hwthreads) / 3600) as int)`, time.Now().Unix()),
   177→			`CAST(SUM(job.num_acc) as int)`,
   178→			fmt.Sprintf(`CAST(ROUND(SUM((CASE WHEN job.job_state = "running" THEN %d - job.start_time ELSE job.duration END) * job.num_acc) / 3600) as int)`, time.Now().Unix()),
   179→		).From("job")
   180→	}
   181→
   182→	for _, f := range filter {
   183→		query = BuildWhereClause(f, query)
   184→	}
   185→
   186→	return query
   187→}
   188→
   189→// JobsStatsGrouped computes comprehensive job statistics grouped by a dimension (user, project, cluster, or subcluster).
   190→//
   191→// This is the primary method for generating aggregated statistics views in the UI, providing
   192→// metrics like total jobs, walltime, and resource usage broken down by the specified grouping.
   193→//
   194→// Parameters:
   195→//   - ctx: Context for security checks and cancellation
   196→//   - filter: Filters to apply (time range, cluster, job state, etc.)
   197→//   - page: Optional pagination (ItemsPerPage: -1 disables pagination)
   198→//   - sortBy: Optional sort column (totalJobs, totalWalltime, totalCoreHours, etc.)
   199→//   - groupBy: Required grouping dimension (User, Project, Cluster, or SubCluster)
   200→//
   201→// Returns a slice of JobsStatistics, one per group, with:
   202→//   - ID: The group identifier (username, project name, cluster name, etc.)
   203→//   - Name: Display name (for users, from hpc_user.name; empty for other groups)
   204→//   - Statistics: totalJobs, totalUsers, totalWalltime, resource usage metrics
   205→//
   206→// Security: Respects user roles via SecurityCheck - users see only their own data unless admin/support.
   207→// Performance: Results are sorted in SQL and pagination applied before scanning rows.
   208→func (r *JobRepository) JobsStatsGrouped(
   209→	ctx context.Context,
   210→	filter []*model.JobFilter,
   211→	page *model.PageRequest,
   212→	sortBy *model.SortByAggregate,
   213→	groupBy *model.Aggregate,
   214→) ([]*model.JobsStatistics, error) {
   215→	start := time.Now()
   216→	col := groupBy2column[*groupBy]
   217→	query := r.buildStatsQuery(filter, col)
   218→
   219→	query, err := SecurityCheck(ctx, query)
   220→	if err != nil {
   221→		return nil, err
   222→	}
   223→
   224→	if sortBy != nil {
   225→		sortBy := sortBy2column[*sortBy]
   226→		query = query.OrderBy(fmt.Sprintf("%s DESC", sortBy))
   227→	}
   228→	if page != nil && page.ItemsPerPage != -1 {
   229→		limit := uint64(page.ItemsPerPage)
   230→		query = query.Offset((uint64(page.Page) - 1) * limit).Limit(limit)
   231→	}
   232→
   233→	rows, err := query.RunWith(r.DB).Query()
   234→	if err != nil {
   235→		cclog.Warn("Error while querying DB for job statistics")
   236→		return nil, err
   237→	}
   238→
   239→	stats := make([]*model.JobsStatistics, 0, 100)
   240→
   241→	for rows.Next() {
   242→		var id sql.NullString
   243→		var name sql.NullString
   244→		var jobs, users, walltime, nodes, nodeHours, cores, coreHours, accs, accHours sql.NullInt64
   245→		if err := rows.Scan(&id, &name, &jobs, &users, &walltime, &nodes, &nodeHours, &cores, &coreHours, &accs, &accHours); err != nil {
   246→			cclog.Warnf("Error while scanning rows: %s", err.Error())
   247→			return nil, err
   248→		}
   249→
   250→		if id.Valid {
   251→			var totalJobs, totalUsers, totalWalltime, totalNodes, totalNodeHours, totalCores, totalCoreHours, totalAccs, totalAccHours int
   252→			var personName string
   253→
   254→			if name.Valid {
   255→				personName = name.String
   256→			}
   257→
   258→			if jobs.Valid {
   259→				totalJobs = int(jobs.Int64)
   260→			}
   261→
   262→			if users.Valid {
   263→				totalUsers = int(users.Int64)
   264→			}
   265→
   266→			if walltime.Valid {
   267→				totalWalltime = int(walltime.Int64)
   268→			}
   269→
   270→			if nodes.Valid {
   271→				totalNodes = int(nodes.Int64)
   272→			}
   273→			if cores.Valid {
   274→				totalCores = int(cores.Int64)
   275→			}
   276→			if accs.Valid {
   277→				totalAccs = int(accs.Int64)
   278→			}
   279→
   280→			if nodeHours.Valid {
   281→				totalNodeHours = int(nodeHours.Int64)
   282→			}
   283→			if coreHours.Valid {
   284→				totalCoreHours = int(coreHours.Int64)
   285→			}
   286→			if accHours.Valid {
   287→				totalAccHours = int(accHours.Int64)
   288→			}
   289→
   290→			if col == "job.hpc_user" {
   291→				// name := r.getUserName(ctx, id.String)
   292→				stats = append(stats,
   293→					&model.JobsStatistics{
   294→						ID:             id.String,
   295→						Name:           personName,
   296→						TotalJobs:      totalJobs,
   297→						TotalWalltime:  totalWalltime,
   298→						TotalNodes:     totalNodes,
   299→						TotalNodeHours: totalNodeHours,
   300→						TotalCores:     totalCores,
   301→						TotalCoreHours: totalCoreHours,
   302→						TotalAccs:      totalAccs,
   303→						TotalAccHours:  totalAccHours,
   304→					})
   305→			} else {
   306→				stats = append(stats,
   307→					&model.JobsStatistics{
   308→						ID:             id.String,
   309→						TotalJobs:      totalJobs,
   310→						TotalUsers:     totalUsers,
   311→						TotalWalltime:  totalWalltime,
   312→						TotalNodes:     totalNodes,
   313→						TotalNodeHours: totalNodeHours,
   314→						TotalCores:     totalCores,
   315→						TotalCoreHours: totalCoreHours,
   316→						TotalAccs:      totalAccs,
   317→						TotalAccHours:  totalAccHours,
   318→					})
   319→			}
   320→		}
   321→	}
   322→
   323→	cclog.Debugf("Timer JobsStatsGrouped %s", time.Since(start))
   324→	return stats, nil
   325→}
   326→
   327→// JobsStats computes overall job statistics across all matching jobs without grouping.
   328→//
   329→// This method provides a single aggregate view of job metrics, useful for dashboard
   330→// summaries and overall system utilization reports.
   331→//
   332→// Parameters:
   333→//   - ctx: Context for security checks and cancellation
   334→//   - filter: Filters to apply (time range, cluster, job state, etc.)
   335→//
   336→// Returns a single-element slice containing aggregate statistics:
   337→//   - totalJobs, totalUsers, totalWalltime
   338→//   - totalNodeHours, totalCoreHours, totalAccHours
   339→//
   340→// Unlike JobsStatsGrouped, this returns overall totals without breaking down by dimension.
   341→// Security checks are applied via SecurityCheck to respect user access levels.
   342→func (r *JobRepository) JobsStats(
   343→	ctx context.Context,
   344→	filter []*model.JobFilter,
   345→) ([]*model.JobsStatistics, error) {
   346→	start := time.Now()
   347→	query := r.buildStatsQuery(filter, "")
   348→	query, err := SecurityCheck(ctx, query)
   349→	if err != nil {
   350→		return nil, err
   351→	}
   352→
   353→	row := query.RunWith(r.DB).QueryRow()
   354→	stats := make([]*model.JobsStatistics, 0, 1)
   355→
   356→	var jobs, users, walltime, nodes, nodeHours, cores, coreHours, accs, accHours sql.NullInt64
   357→	if err := row.Scan(&jobs, &users, &walltime, &nodes, &nodeHours, &cores, &coreHours, &accs, &accHours); err != nil {
   358→		cclog.Warn("Error while scanning rows")
   359→		return nil, err
   360→	}
   361→
   362→	if jobs.Valid {
   363→		var totalNodeHours, totalCoreHours, totalAccHours int
   364→
   365→		if nodeHours.Valid {
   366→			totalNodeHours = int(nodeHours.Int64)
   367→		}
   368→		if coreHours.Valid {
   369→			totalCoreHours = int(coreHours.Int64)
   370→		}
   371→		if accHours.Valid {
   372→			totalAccHours = int(accHours.Int64)
   373→		}
   374→		stats = append(stats,
   375→			&model.JobsStatistics{
   376→				TotalJobs:      int(jobs.Int64),
   377→				TotalUsers:     int(users.Int64),
   378→				TotalWalltime:  int(walltime.Int64),
   379→				TotalNodeHours: totalNodeHours,
   380→				TotalCoreHours: totalCoreHours,
   381→				TotalAccHours:  totalAccHours,
   382→			})
   383→	}
   384→
   385→	cclog.Debugf("Timer JobStats %s", time.Since(start))
   386→	return stats, nil
   387→}
   388→
   389→// LoadJobStat retrieves a specific statistic for a metric from a job's statistics.
   390→// Returns 0.0 if the metric is not found or statType is invalid.
   391→//
   392→// Parameters:
   393→//   - job: Job struct with populated Statistics field
   394→//   - metric: Name of the metric to query (e.g., "cpu_load", "mem_used")
   395→//   - statType: Type of statistic: "avg", "min", or "max"
   396→//
   397→// Returns the requested statistic value or 0.0 if not found.
   398→func LoadJobStat(job *schema.Job, metric string, statType string) float64 {
   399→	if stats, ok := job.Statistics[metric]; ok {
   400→		switch statType {
   401→		case "avg":
   402→			return stats.Avg
   403→		case "max":
   404→			return stats.Max
   405→		case "min":
   406→			return stats.Min
   407→		default:
   408→			cclog.Errorf("Unknown stat type %s", statType)
   409→		}
   410→	}
   411→
   412→	return 0.0
   413→}
   414→
   415→// JobCountGrouped counts jobs grouped by a dimension without computing detailed statistics.
   416→//
   417→// This is a lightweight alternative to JobsStatsGrouped when only job counts are needed,
   418→// avoiding the overhead of calculating walltime and resource usage metrics.
   419→//
   420→// Parameters:
   421→//   - ctx: Context for security checks
   422→//   - filter: Filters to apply
   423→//   - groupBy: Grouping dimension (User, Project, Cluster, or SubCluster)
   424→//
   425→// Returns JobsStatistics with only ID and TotalJobs populated for each group.
   426→func (r *JobRepository) JobCountGrouped(
   427→	ctx context.Context,
   428→	filter []*model.JobFilter,
   429→	groupBy *model.Aggregate,
   430→) ([]*model.JobsStatistics, error) {
   431→	start := time.Now()
   432→	col := groupBy2column[*groupBy]
   433→	query := r.buildCountQuery(filter, "", col)
   434→	query, err := SecurityCheck(ctx, query)
   435→	if err != nil {
   436→		return nil, err
   437→	}
   438→	rows, err := query.RunWith(r.DB).Query()
   439→	if err != nil {
   440→		cclog.Warn("Error while querying DB for job statistics")
   441→		return nil, err
   442→	}
   443→
   444→	stats := make([]*model.JobsStatistics, 0, 100)
   445→
   446→	for rows.Next() {
   447→		var id sql.NullString
   448→		var cnt sql.NullInt64
   449→		if err := rows.Scan(&id, &cnt); err != nil {
   450→			cclog.Warn("Error while scanning rows")
   451→			return nil, err
   452→		}
   453→		if id.Valid {
   454→			stats = append(stats,
   455→				&model.JobsStatistics{
   456→					ID:        id.String,
   457→					TotalJobs: int(cnt.Int64),
   458→				})
   459→		}
   460→	}
   461→
   462→	cclog.Debugf("Timer JobCountGrouped %s", time.Since(start))
   463→	return stats, nil
   464→}
   465→
   466→// AddJobCountGrouped augments existing statistics with additional job counts by category.
   467→//
   468→// This method enriches JobsStatistics returned by JobsStatsGrouped or JobCountGrouped
   469→// with counts of running or short-running (based on ShortRunningJobsDuration) jobs, matched by group ID.
   470→//
   471→// Parameters:
   472→//   - ctx: Context for security checks
   473→//   - filter: Filters to apply
   474→//   - groupBy: Grouping dimension (must match the dimension used for stats parameter)
   475→//   - stats: Existing statistics to augment (modified in-place by ID matching)
   476→//   - kind: "running" to add RunningJobs count, "short" to add ShortJobs count
   477→//
   478→// Returns the same stats slice with RunningJobs or ShortJobs fields populated per group.
   479→// Groups without matching jobs will have 0 for the added field.
   480→func (r *JobRepository) AddJobCountGrouped(
   481→	ctx context.Context,
   482→	filter []*model.JobFilter,
   483→	groupBy *model.Aggregate,
   484→	stats []*model.JobsStatistics,
   485→	kind string,
   486→) ([]*model.JobsStatistics, error) {
   487→	start := time.Now()
   488→	col := groupBy2column[*groupBy]
   489→	query := r.buildCountQuery(filter, kind, col)
   490→	query, err := SecurityCheck(ctx, query)
   491→	if err != nil {
   492→		return nil, err
   493→	}
   494→	rows, err := query.RunWith(r.DB).Query()
   495→	if err != nil {
   496→		cclog.Warn("Error while querying DB for job statistics")
   497→		return nil, err
   498→	}
   499→
   500→	counts := make(map[string]int)
   501→
   502→	for rows.Next() {
   503→		var id sql.NullString
   504→		var cnt sql.NullInt64
   505→		if err := rows.Scan(&id, &cnt); err != nil {
   506→			cclog.Warn("Error while scanning rows")
   507→			return nil, err
   508→		}
   509→		if id.Valid {
   510→			counts[id.String] = int(cnt.Int64)
   511→		}
   512→	}
   513→
   514→	switch kind {
   515→	case "running":
   516→		for _, s := range stats {
   517→			s.RunningJobs = counts[s.ID]
   518→		}
   519→	case "short":
   520→		for _, s := range stats {
   521→			s.ShortJobs = counts[s.ID]
   522→		}
   523→	}
   524→
   525→	cclog.Debugf("Timer AddJobCountGrouped %s", time.Since(start))
   526→	return stats, nil
   527→}
   528→
   529→// AddJobCount augments existing overall statistics with additional job counts by category.
   530→//
   531→// Similar to AddJobCountGrouped but for ungrouped statistics. Applies the same count
   532→// to all statistics entries (typically just one).
   533→//
   534→// Parameters:
   535→//   - ctx: Context for security checks
   536→//   - filter: Filters to apply
   537→//   - stats: Existing statistics to augment (modified in-place)
   538→//   - kind: "running" to add RunningJobs count, "short" to add ShortJobs count
   539→//
   540→// Returns the same stats slice with RunningJobs or ShortJobs fields set to the total count.
   541→func (r *JobRepository) AddJobCount(
   542→	ctx context.Context,
   543→	filter []*model.JobFilter,
   544→	stats []*model.JobsStatistics,
   545→	kind string,
   546→) ([]*model.JobsStatistics, error) {
   547→	start := time.Now()
   548→	query := r.buildCountQuery(filter, kind, "")
   549→	query, err := SecurityCheck(ctx, query)
   550→	if err != nil {
   551→		return nil, err
   552→	}
   553→	rows, err := query.RunWith(r.DB).Query()
   554→	if err != nil {
   555→		cclog.Warn("Error while querying DB for job statistics")
   556→		return nil, err
   557→	}
   558→
   559→	var count int
   560→
   561→	for rows.Next() {
   562→		var cnt sql.NullInt64
   563→		if err := rows.Scan(&cnt); err != nil {
   564→			cclog.Warn("Error while scanning rows")
   565→			return nil, err
   566→		}
   567→
   568→		count = int(cnt.Int64)
   569→	}
   570→
   571→	switch kind {
   572→	case "running":
   573→		for _, s := range stats {
   574→			s.RunningJobs = count
   575→		}
   576→	case "short":
   577→		for _, s := range stats {
   578→			s.ShortJobs = count
   579→		}
   580→	}
   581→
   582→	cclog.Debugf("Timer AddJobCount %s", time.Since(start))
   583→	return stats, nil
   584→}
   585→
   586→// AddHistograms augments statistics with distribution histograms for job properties.
   587→//
   588→// Generates histogram data for visualization of job duration, node count, core count,
   589→// and accelerator count distributions. Duration histogram uses intelligent binning based
   590→// on the requested resolution.
   591→//
   592→// Parameters:
   593→//   - ctx: Context for security checks
   594→//   - filter: Filters to apply to jobs included in histograms
   595→//   - stat: Statistics struct to augment (modified in-place)
   596→//   - durationBins: Bin size - "1m", "10m", "1h", "6h", "12h", or "24h" (default)
   597→//
   598→// Populates these fields in stat:
   599→//   - HistDuration: Job duration distribution (zero-padded bins)
   600→//   - HistNumNodes: Node count distribution
   601→//   - HistNumCores: Core (hwthread) count distribution
   602→//   - HistNumAccs: Accelerator count distribution
   603→//
   604→// Duration bins are pre-initialized with zeros to ensure consistent ranges for visualization.
   605→// Bin size determines both the width and maximum duration displayed (e.g., "1h" = 48 bins × 1h = 48h max).
   606→func (r *JobRepository) AddHistograms(
   607→	ctx context.Context,
   608→	filter []*model.JobFilter,
   609→	stat *model.JobsStatistics,
   610→	durationBins *string,
   611→) (*model.JobsStatistics, error) {
   612→	start := time.Now()
   613→
   614→	var targetBinCount int
   615→	var targetBinSize int
   616→	switch *durationBins {
   617→	case "1m": // 1 Minute Bins + Max 60 Bins -> Max 60 Minutes
   618→		targetBinCount = 60
   619→		targetBinSize = 60
   620→	case "10m": // 10 Minute Bins + Max 72 Bins -> Max 12 Hours
   621→		targetBinCount = 72
   622→		targetBinSize = 600
   623→	case "1h": // 1 Hour Bins + Max 48 Bins -> Max 48 Hours
   624→		targetBinCount = 48
   625→		targetBinSize = 3600
   626→	case "6h": // 6 Hour Bins + Max 12 Bins -> Max 3 Days
   627→		targetBinCount = 12
   628→		targetBinSize = 21600
   629→	case "12h": // 12 hour Bins + Max 14 Bins -> Max 7 Days
   630→		targetBinCount = 14
   631→		targetBinSize = 43200
   632→	default: // 24h
   633→		targetBinCount = 24
   634→		targetBinSize = 3600
   635→	}
   636→
   637→	var err error
   638→	// Return X-Values always as seconds, will be formatted into minutes and hours in frontend
   639→	value := fmt.Sprintf(`CAST(ROUND(((CASE WHEN job.job_state = "running" THEN %d - job.start_time ELSE job.duration END) / %d) + 1) as int) as value`, time.Now().Unix(), targetBinSize)
   640→	stat.HistDuration, err = r.jobsDurationStatisticsHistogram(ctx, value, filter, targetBinSize, &targetBinCount)
   641→	if err != nil {
   642→		cclog.Warn("Error while loading job statistics histogram: job duration")
   643→		return nil, err
   644→	}
   645→
   646→	stat.HistNumNodes, err = r.jobsStatisticsHistogram(ctx, "job.num_nodes as value", filter)
   647→	if err != nil {
   648→		cclog.Warn("Error while loading job statistics histogram: num nodes")
   649→		return nil, err
   650→	}
   651→
   652→	stat.HistNumCores, err = r.jobsStatisticsHistogram(ctx, "job.num_hwthreads as value", filter)
   653→	if err != nil {
   654→		cclog.Warn("Error while loading job statistics histogram: num hwthreads")
   655→		return nil, err
   656→	}
   657→
   658→	stat.HistNumAccs, err = r.jobsStatisticsHistogram(ctx, "job.num_acc as value", filter)
   659→	if err != nil {
   660→		cclog.Warn("Error while loading job statistics histogram: num acc")
   661→		return nil, err
   662→	}
   663→
   664→	cclog.Debugf("Timer AddHistograms %s", time.Since(start))
   665→	return stat, nil
   666→}
   667→
   668→// AddMetricHistograms augments statistics with distribution histograms for job metrics.
   669→//
   670→// Generates histogram data for metrics like CPU load, memory usage, etc. Handles running
   671→// and completed jobs differently: running jobs load data from metric backend, completed jobs
   672→// use footprint data from database.
   673→//
   674→// Parameters:
   675→//   - ctx: Context for security checks
   676→//   - filter: Filters to apply (MUST contain State filter for running jobs)
   677→//   - metrics: List of metric names to histogram (e.g., ["cpu_load", "mem_used"])
   678→//   - stat: Statistics struct to augment (modified in-place)
   679→//   - targetBinCount: Number of histogram bins (default: 10)
   680→//
   681→// Populates HistMetrics field in stat with MetricHistoPoints for each metric.
   682→//
   683→// Binning algorithm:
   684→//   - Values normalized to metric's peak value from cluster configuration
   685→//   - Bins evenly distributed from 0 to peak
   686→//   - Pre-initialized with zeros for consistent visualization
   687→//
   688→// Limitations:
   689→//   - Running jobs: Limited to 5000 jobs for performance
   690→//   - Requires valid cluster configuration with metric peak values
   691→//   - Uses footprint statistic (avg/max/min) configured per metric
   692→func (r *JobRepository) AddMetricHistograms(
   693→	ctx context.Context,
   694→	filter []*model.JobFilter,
   695→	metrics []string,
   696→	stat *model.JobsStatistics,
   697→	targetBinCount *int,
   698→) (*model.JobsStatistics, error) {
   699→	start := time.Now()
   700→
   701→	// Running Jobs Only: First query jobdata from sqlite, then query data and make bins
   702→	for _, f := range filter {
   703→		if f.State != nil {
   704→			if len(f.State) == 1 && f.State[0] == "running" {
   705→				stat.HistMetrics = r.runningJobsMetricStatisticsHistogram(ctx, metrics, filter, targetBinCount)
   706→				cclog.Debugf("Timer AddMetricHistograms %s", time.Since(start))
   707→				return stat, nil
   708→			}
   709→		}
   710→	}
   711→
   712→	// All other cases: Query and make bins in sqlite directly
   713→	for _, m := range metrics {
   714→		metricHisto, err := r.jobsMetricStatisticsHistogram(ctx, m, filter, targetBinCount)
   715→		if err != nil {
   716→			cclog.Warnf("Error while loading job metric statistics histogram: %s", m)
   717→			continue
   718→		}
   719→		stat.HistMetrics = append(stat.HistMetrics, metricHisto)
   720→	}
   721→
   722→	cclog.Debugf("Timer AddMetricHistograms %s", time.Since(start))
   723→	return stat, nil
   724→}
   725→
   726→// jobsStatisticsHistogram generates a simple histogram by grouping on a column value.
   727→//
   728→// Used for histograms where the column value directly represents the bin (e.g., node count, core count).
   729→// Unlike duration/metric histograms, this doesn't pre-initialize bins with zeros.
   730→//
   731→// Parameters:
   732→//   - value: SQL expression that produces the histogram value, aliased as "value"
   733→//   - filters: Job filters to apply
   734→//
   735→// Returns histogram points with Value (from column) and Count (number of jobs).
   736→func (r *JobRepository) jobsStatisticsHistogram(
   737→	ctx context.Context,
   738→	value string,
   739→	filters []*model.JobFilter,
   740→) ([]*model.HistoPoint, error) {
   741→	start := time.Now()
   742→	query, qerr := SecurityCheck(ctx,
   743→		sq.Select(value, "COUNT(job.id) AS count").From("job"))
   744→
   745→	if qerr != nil {
   746→		return nil, qerr
   747→	}
   748→
   749→	for _, f := range filters {
   750→		query = BuildWhereClause(f, query)
   751→	}
   752→
   753→	rows, err := query.GroupBy("value").RunWith(r.DB).Query()
   754→	if err != nil {
   755→		cclog.Error("Error while running query")
   756→		return nil, err
   757→	}
   758→
   759→	points := make([]*model.HistoPoint, 0)
   760→	// is it possible to introduce zero values here? requires info about bincount
   761→	for rows.Next() {
   762→		point := model.HistoPoint{}
   763→		if err := rows.Scan(&point.Value, &point.Count); err != nil {
   764→			cclog.Warn("Error while scanning rows")
   765→			return nil, err
   766→		}
   767→
   768→		points = append(points, &point)
   769→	}
   770→	cclog.Debugf("Timer jobsStatisticsHistogram %s", time.Since(start))
   771→	return points, nil
   772→}
   773→
   774→// jobsDurationStatisticsHistogram generates a duration histogram with pre-initialized bins.
   775→//
   776→// Bins are zero-padded to provide consistent ranges for visualization, unlike simple
   777→// histograms which only return bins with data. The value parameter should compute
   778→// the bin number from job duration.
   779→//
   780→// Parameters:
   781→//   - value: SQL expression computing bin number from duration, aliased as "value"
   782→//   - filters: Job filters to apply
   783→//   - binSizeSeconds: Width of each bin in seconds
   784→//   - targetBinCount: Number of bins to pre-initialize
   785→//
   786→// Returns histogram points with Value (bin_number × binSizeSeconds) and Count.
   787→// All bins from 1 to targetBinCount are returned, with Count=0 for empty bins.
   788→//
   789→// Algorithm:
   790→//  1. Pre-initialize targetBinCount bins with zero counts
   791→//  2. Query database for actual counts per bin
   792→//  3. Match query results to pre-initialized bins by value
   793→//  4. Bins without matches remain at zero
   794→func (r *JobRepository) jobsDurationStatisticsHistogram(
   795→	ctx context.Context,
   796→	value string,
   797→	filters []*model.JobFilter,
   798→	binSizeSeconds int,
   799→	targetBinCount *int,
   800→) ([]*model.HistoPoint, error) {
   801→	start := time.Now()
   802→	query, qerr := SecurityCheck(ctx,
   803→		sq.Select(value, "COUNT(job.id) AS count").From("job"))
   804→
   805→	if qerr != nil {
   806→		return nil, qerr
   807→	}
   808→
   809→	// Each bin represents a duration range: bin N = [N*binSizeSeconds, (N+1)*binSizeSeconds)
   810→	// Example: binSizeSeconds=3600 (1 hour), bin 1 = 0-1h, bin 2 = 1-2h, etc.
   811→	points := make([]*model.HistoPoint, 0)
   812→	for i := 1; i <= *targetBinCount; i++ {
   813→		point := model.HistoPoint{Value: i * binSizeSeconds, Count: 0}
   814→		points = append(points, &point)
   815→	}
   816→
   817→	for _, f := range filters {
   818→		query = BuildWhereClause(f, query)
   819→	}
   820→
   821→	rows, err := query.GroupBy("value").RunWith(r.DB).Query()
   822→	if err != nil {
   823→		cclog.Error("Error while running query")
   824→		return nil, err
   825→	}
   826→
   827→	// Match query results to pre-initialized bins.
   828→	// point.Value from query is the bin number; multiply by binSizeSeconds to match bin.Value.
   829→	for rows.Next() {
   830→		point := model.HistoPoint{}
   831→		if err := rows.Scan(&point.Value, &point.Count); err != nil {
   832→			cclog.Warn("Error while scanning rows")
   833→			return nil, err
   834→		}
   835→
   836→		for _, e := range points {
   837→			if e.Value == (point.Value * binSizeSeconds) {
   838→				e.Count = point.Count
   839→				break
   840→			}
   841→		}
   842→	}
   843→
   844→	cclog.Debugf("Timer jobsStatisticsHistogram %s", time.Since(start))
   845→	return points, nil
   846→}
   847→
   848→// jobsMetricStatisticsHistogram generates a metric histogram using footprint data from completed jobs.
   849→//
   850→// Values are normalized to the metric's peak value and distributed into bins. The algorithm
   851→// is based on SQL histogram generation techniques, extracting metric values from JSON footprint
   852→// and computing bin assignments in SQL.
   853→//
   854→// Parameters:
   855→//   - metric: Metric name (e.g., "cpu_load", "mem_used")
   856→//   - filters: Job filters to apply
   857→//   - bins: Number of bins to generate
   858→//
   859→// Returns MetricHistoPoints with metric name, unit, footprint stat type, and binned data.
   860→//
   861→// Algorithm:
   862→//  1. Determine peak value from cluster configuration (filtered cluster or max across all)
   863→//  2. Generate SQL that extracts footprint value, normalizes to [0,1], multiplies by bin count
   864→//  3. Pre-initialize bins with min/max ranges based on peak value
   865→//  4. Query database for counts per bin
   866→//  5. Match results to pre-initialized bins
   867→//
   868→// Special handling: Values exactly equal to peak are forced into the last bin by multiplying
   869→// peak by 0.999999999 to avoid creating an extra bin.
   870→func (r *JobRepository) jobsMetricStatisticsHistogram(
   871→	ctx context.Context,
   872→	metric string,
   873→	filters []*model.JobFilter,
   874→	bins *int,
   875→) (*model.MetricHistoPoints, error) {
   876→	// Peak value defines the upper bound for binning: values are distributed across
   877→	// bins from 0 to peak. First try to get peak from filtered cluster, otherwise
   878→	// scan all clusters to find the maximum peak value.
   879→	var metricConfig *schema.MetricConfig
   880→	var peak float64
   881→	var unit string
   882→	var footprintStat string
   883→
   884→	// Try to get metric config from filtered cluster
   885→	for _, f := range filters {
   886→		if f.Cluster != nil {
   887→			metricConfig = archive.GetMetricConfig(*f.Cluster.Eq, metric)
   888→			peak = metricConfig.Peak
   889→			unit = metricConfig.Unit.Prefix + metricConfig.Unit.Base
   890→			footprintStat = metricConfig.Footprint
   891→			cclog.Debugf("Cluster %s filter found with peak %f for %s", *f.Cluster.Eq, peak, metric)
   892→		}
   893→	}
   894→
   895→	// If no cluster filter or peak not found, find largest peak across all clusters
   896→	// This ensures histogram can accommodate all possible values
   897→	if peak == 0.0 {
   898→		for _, c := range archive.Clusters {
   899→			for _, m := range c.MetricConfig {
   900→				if m.Name == metric {
   901→					if m.Peak > peak {
   902→						peak = m.Peak
   903→					}
   904→					if unit == "" {
   905→						unit = m.Unit.Prefix + m.Unit.Base
   906→					}
   907→					if footprintStat == "" {
   908→						footprintStat = m.Footprint
   909→					}
   910→				}
   911→			}
   912→		}
   913→	}
   914→
   915→	// Construct SQL histogram bins using normalized values.
   916→	// Algorithm based on: https://jereze.com/code/sql-histogram/ (modified)
   917→	start := time.Now()
   918→
   919→	// Bin calculation formula:
   920→	//   bin_number = CAST( (value / peak) * num_bins AS INTEGER ) + 1
   921→	// Special case: value == peak would create bin N+1, so we test for equality
   922→	// and multiply peak by 0.999999999 to force it into bin N.
   923→	binQuery := fmt.Sprintf(`CAST(
   924→		((case when json_extract(footprint, "$.%s") = %f then %f*0.999999999 else json_extract(footprint, "$.%s") end) / %f)
   925→		* %v as INTEGER )`,
   926→		(metric + "_" + footprintStat), peak, peak, (metric + "_" + footprintStat), peak, *bins)
   927→
   928→	mainQuery := sq.Select(
   929→		fmt.Sprintf(`%s + 1 as bin`, binQuery),
   930→		`count(*) as count`,
   931→	).From("job").Where(
   932→		"JSON_VALID(footprint)",
   933→	).Where(fmt.Sprintf(`json_extract(footprint, "$.%s") is not null and json_extract(footprint, "$.%s") <= %f`, (metric + "_" + footprintStat), (metric + "_" + footprintStat), peak))
   934→
   935→	mainQuery, qerr := SecurityCheck(ctx, mainQuery)
   936→	if qerr != nil {
   937→		return nil, qerr
   938→	}
   939→
   940→	for _, f := range filters {
   941→		mainQuery = BuildWhereClause(f, mainQuery)
   942→	}
   943→
   944→	mainQuery = mainQuery.GroupBy("bin").OrderBy("bin")
   945→
   946→	rows, err := mainQuery.RunWith(r.DB).Query()
   947→	if err != nil {
   948→		cclog.Errorf("Error while running mainQuery: %s", err)
   949→		return nil, err
   950→	}
   951→
   952→	// Pre-initialize bins with calculated min/max ranges.
   953→	// Example: peak=1000, bins=10 -> bin 1=[0,100), bin 2=[100,200), ..., bin 10=[900,1000]
   954→	points := make([]*model.MetricHistoPoint, 0)
   955→	binStep := int(peak) / *bins
   956→	for i := 1; i <= *bins; i++ {
   957→		binMin := (binStep * (i - 1))
   958→		binMax := (binStep * i)
   959→		epoint := model.MetricHistoPoint{Bin: &i, Count: 0, Min: &binMin, Max: &binMax}
   960→		points = append(points, &epoint)
   961→	}
   962→
   963→	// Match query results to pre-initialized bins.
   964→	for rows.Next() {
   965→		rpoint := model.MetricHistoPoint{}
   966→		if err := rows.Scan(&rpoint.Bin, &rpoint.Count); err != nil {
   967→			cclog.Warnf("Error while scanning rows for %s", metric)
   968→			return nil, err
   969→		}
   970→
   971→		for _, e := range points {
   972→			if e.Bin != nil && rpoint.Bin != nil && *e.Bin == *rpoint.Bin {
   973→				e.Count = rpoint.Count
   974→				break
   975→			}
   976→		}
   977→	}
   978→
   979→	result := model.MetricHistoPoints{Metric: metric, Unit: unit, Stat: &footprintStat, Data: points}
   980→
   981→	cclog.Debugf("Timer jobsStatisticsHistogram %s", time.Since(start))
   982→	return &result, nil
   983→}
   984→
   985→// runningJobsMetricStatisticsHistogram generates metric histograms for running jobs using live data.
   986→//
   987→// Unlike completed jobs which use footprint data from the database, running jobs require
   988→// fetching current metric averages from the metric backend (via metricdispatch).
   989→//
   990→// Parameters:
   991→//   - metrics: List of metric names
   992→//   - filters: Job filters (should filter to running jobs only)
   993→//   - bins: Number of histogram bins
   994→//
   995→// Returns slice of MetricHistoPoints, one per metric.
   996→//
   997→// Limitations:
   998→//   - Maximum 5000 jobs (returns nil if more jobs match)
   999→//   - Requires metric backend availability
  1000→//   - Bins based on metric peak values from cluster configuration
  1001→//
  1002→// Algorithm:
  1003→//  1. Query first 5001 jobs to check count limit
  1004→//  2. Load metric averages for all jobs via metricdispatch
  1005→//  3. For each metric, create bins based on peak value
  1006→//  4. Iterate averages and count jobs per bin
  1007→func (r *JobRepository) runningJobsMetricStatisticsHistogram(
  1008→	ctx context.Context,
  1009→	metrics []string,
  1010→	filters []*model.JobFilter,
  1011→	bins *int,
  1012→) []*model.MetricHistoPoints {
  1013→	// Get Jobs
  1014→	jobs, err := r.QueryJobs(ctx, filters, &model.PageRequest{Page: 1, ItemsPerPage: 5000 + 1}, nil)
  1015→	if err != nil {
  1016→		cclog.Errorf("Error while querying jobs for footprint: %s", err)
  1017→		return nil
  1018→	}
  1019→	if len(jobs) > 5000 {
  1020→		cclog.Errorf("too many jobs matched (max: %d)", 5000)
  1021→		return nil
  1022→	}
  1023→
  1024→	// Get AVGs from metric repo
  1025→	avgs := make([][]schema.Float, len(metrics))
  1026→	for i := range avgs {
  1027→		avgs[i] = make([]schema.Float, 0, len(jobs))
  1028→	}
  1029→
  1030→	for _, job := range jobs {
  1031→		if job.MonitoringStatus == schema.MonitoringStatusDisabled || job.MonitoringStatus == schema.MonitoringStatusArchivingFailed {
  1032→			continue
  1033→		}
  1034→
  1035→		if err := metricdispatch.LoadAverages(job, metrics, avgs, ctx); err != nil {
  1036→			cclog.Errorf("Error while loading averages for histogram: %s", err)
  1037→			return nil
  1038→		}
  1039→	}
  1040→
  1041→	// Iterate metrics to fill endresult
  1042→	data := make([]*model.MetricHistoPoints, 0)
  1043→	for idx, metric := range metrics {
  1044→		// Get specific Peak or largest Peak
  1045→		var metricConfig *schema.MetricConfig
  1046→		var peak float64
  1047→		var unit string
  1048→
  1049→		for _, f := range filters {
  1050→			if f.Cluster != nil {
  1051→				metricConfig = archive.GetMetricConfig(*f.Cluster.Eq, metric)
  1052→				peak = metricConfig.Peak
  1053→				unit = metricConfig.Unit.Prefix + metricConfig.Unit.Base
  1054→			}
  1055→		}
  1056→
  1057→		if peak == 0.0 {
  1058→			for _, c := range archive.Clusters {
  1059→				for _, m := range c.MetricConfig {
  1060→					if m.Name == metric {
  1061→						if m.Peak > peak {
  1062→							peak = m.Peak
  1063→						}
  1064→						if unit == "" {
  1065→							unit = m.Unit.Prefix + m.Unit.Base
  1066→						}
  1067→					}
  1068→				}
  1069→			}
  1070→		}
  1071→
  1072→		// Make and fill bins
  1073→		peakBin := int(peak) / *bins
  1074→
  1075→		points := make([]*model.MetricHistoPoint, 0)
  1076→		for b := 0; b < *bins; b++ {
  1077→			count := 0
  1078→			bindex := b + 1
  1079→			bmin := peakBin * b
  1080→			bmax := peakBin * (b + 1)
  1081→
  1082→			// Iterate AVG values for indexed metric and count for bins
  1083→			for _, val := range avgs[idx] {
  1084→				if int(val) >= bmin && int(val) < bmax {
  1085→					count += 1
  1086→				}
  1087→			}
  1088→
  1089→			// Append Bin to Metric Result Array
  1090→			point := model.MetricHistoPoint{Bin: &bindex, Count: count, Min: &bmin, Max: &bmax}
  1091→			points = append(points, &point)
  1092→		}
  1093→
  1094→		// Append Metric Result Array to final results array
  1095→		result := model.MetricHistoPoints{Metric: metric, Unit: unit, Data: points}
  1096→		data = append(data, &result)
  1097→	}
  1098→
  1099→	return data
  1100→}
  1101→