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

// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.
// All rights reserved. This file is part of cc-backend.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

// This file contains job statistics and histogram generation functionality for the JobRepository.
//
// # Job Statistics
//
// The statistics methods provide aggregated metrics about jobs including total jobs, users,
// walltime, and resource usage (nodes, cores, accelerators). Statistics can be computed:
//   - Overall (JobsStats): Single aggregate across all matching jobs
//   - Grouped (JobsStatsGrouped): Aggregated by user, project, cluster, or subcluster
//   - Counts (JobCountGrouped, AddJobCount): Simple job counts with optional filtering
//
// All statistics methods support filtering via JobFilter and respect security contexts.
//
// # Histograms
//
// Histogram methods generate distribution data for visualization:
//   - Duration, nodes, cores, accelerators (AddHistograms)
//   - Job metrics like CPU load, memory usage (AddMetricHistograms)
//
// Histograms use intelligent binning:
//   - Duration: Variable bin sizes (1m, 10m, 1h, 6h, 12h, 24h) with zero-padding
//   - Resources: Natural value-based bins
//   - Metrics: Normalized to peak values with configurable bin counts
//
// # Running vs. Completed Jobs
//
// Statistics handle running jobs specially:
//   - Duration calculated as (now - start_time) for running jobs
//   - Metric histograms for running jobs load data from metric backend instead of footprint
//   - Job state filtering distinguishes running/completed jobs
//
// # Performance Considerations
//
// - All queries use prepared statements via stmtCache
// - Complex aggregations use SQL for efficiency
// - Histogram pre-initialization ensures consistent bin ranges
// - Metric histogram queries limited to 5000 jobs for running job analysis

package repository

import (
	"context"
	"database/sql"
	"fmt"
	"time"

	"github.com/ClusterCockpit/cc-backend/internal/config"
	"github.com/ClusterCockpit/cc-backend/internal/graph/model"
	"github.com/ClusterCockpit/cc-backend/internal/metricdispatch"
	"github.com/ClusterCockpit/cc-backend/pkg/archive"
	cclog "github.com/ClusterCockpit/cc-lib/v2/ccLogger"
	"github.com/ClusterCockpit/cc-lib/v2/schema"
	sq "github.com/Masterminds/squirrel"
)

// groupBy2column maps GraphQL Aggregate enum values to their corresponding database column names.
// Used by JobsStatsGrouped and JobCountGrouped to translate user-facing grouping dimensions
// into SQL GROUP BY clauses. GraphQL validation ensures only valid enum values are accepted.
var groupBy2column = map[model.Aggregate]string{
	model.AggregateUser:       "job.hpc_user",
	model.AggregateProject:    "job.project",
	model.AggregateCluster:    "job.cluster",
	model.AggregateSubcluster: "job.subcluster",
}

// sortBy2column maps GraphQL SortByAggregate enum values to their corresponding computed column names.
// Used by JobsStatsGrouped to translate sort preferences into SQL ORDER BY clauses.
// Column names match the AS aliases used in buildStatsQuery.
var sortBy2column = map[model.SortByAggregate]string{
	model.SortByAggregateTotaljobs:      "totalJobs",
	model.SortByAggregateTotalusers:     "totalUsers",
	model.SortByAggregateTotalwalltime:  "totalWalltime",
	model.SortByAggregateTotalnodes:     "totalNodes",
	model.SortByAggregateTotalnodehours: "totalNodeHours",
	model.SortByAggregateTotalcores:     "totalCores",
	model.SortByAggregateTotalcorehours: "totalCoreHours",
	model.SortByAggregateTotalaccs:      "totalAccs",
	model.SortByAggregateTotalacchours:  "totalAccHours",
}

// buildCountQuery constructs a SQL query to count jobs with optional grouping and filtering.
//
// Parameters:
//   - filter: Job filters to apply (cluster, user, time range, etc.)
//   - kind: Special filter - "running" for running jobs only, "short" for jobs under threshold
//   - col: Column name to GROUP BY; empty string for total count without grouping
//
// Returns a SelectBuilder that produces either:
//   - Single count: COUNT(job.id) when col is empty
//   - Grouped counts: col, COUNT(job.id) when col is specified
//
// The kind parameter enables counting specific job categories:
//   - "running": Only jobs with job_state = 'running'
//   - "short": Only jobs with duration < ShortRunningJobsDuration config value
//   - empty: All jobs matching filters
func (r *JobRepository) buildCountQuery(
	filter []*model.JobFilter,
	kind string,
	col string,
) sq.SelectBuilder {
	var query sq.SelectBuilder

	if col != "" {
		query = sq.Select(col, "COUNT(*)").From("job").GroupBy(col)
	} else {
		query = sq.Select("COUNT(*)").From("job")
	}

	switch kind {
	case "running":
		query = query.Where("job.job_state = ?", "running")
	case "short":
		query = query.Where("job.duration < ?", config.Keys.ShortRunningJobsDuration)
	}

	for _, f := range filter {
		query = BuildWhereClause(f, query)
	}

	return query
}

// buildStatsQuery constructs a SQL query to compute job statistics with optional grouping.
// Only requested columns are computed; unrequested columns select 0 as placeholder.
//
// Parameters:
//   - filter: Job filters to apply (cluster, user, time range, etc.)
//   - col: Column name to GROUP BY; empty string for overall statistics without grouping
//   - shortThreshold: Duration threshold in seconds for counting short-running jobs
//   - reqFields: Set of requested field names; nil means compute all fields
func (r *JobRepository) buildStatsQuery(
	filter []*model.JobFilter,
	col string,
	shortThreshold int,
	reqFields map[string]bool,
) sq.SelectBuilder {
	now := time.Now().Unix()

	// Helper: return real expression if field is requested (or reqFields is nil), else "0 as alias"
	need := func(field string) bool {
		return reqFields == nil || reqFields[field]
	}
	durationExpr := fmt.Sprintf(`(CASE WHEN job.job_state = 'running' THEN %d - job.start_time ELSE job.duration END)`, now)

	// Build column list
	columns := make([]string, 0, 14)

	if col != "" {
		columns = append(columns, col)
	}

	columns = append(columns, "COUNT(*) as totalJobs")

	if need("totalUsers") && col != "job.hpc_user" {
		columns = append(columns, "COUNT(DISTINCT job.hpc_user) AS totalUsers")
	} else {
		columns = append(columns, "0 AS totalUsers")
	}

	if need("totalWalltime") {
		columns = append(columns, fmt.Sprintf(`CAST(ROUND(SUM(%s) / 3600) as int) as totalWalltime`, durationExpr))
	} else {
		columns = append(columns, "0 as totalWalltime")
	}

	if need("totalNodes") {
		columns = append(columns, `CAST(SUM(job.num_nodes) as int) as totalNodes`)
	} else {
		columns = append(columns, "0 as totalNodes")
	}

	if need("totalNodeHours") {
		columns = append(columns, fmt.Sprintf(`CAST(ROUND(SUM(%s * job.num_nodes) / 3600) as int) as totalNodeHours`, durationExpr))
	} else {
		columns = append(columns, "0 as totalNodeHours")
	}

	if need("totalCores") {
		columns = append(columns, `CAST(SUM(job.num_hwthreads) as int) as totalCores`)
	} else {
		columns = append(columns, "0 as totalCores")
	}

	if need("totalCoreHours") {
		columns = append(columns, fmt.Sprintf(`CAST(ROUND(SUM(%s * job.num_hwthreads) / 3600) as int) as totalCoreHours`, durationExpr))
	} else {
		columns = append(columns, "0 as totalCoreHours")
	}

	if need("totalAccs") {
		columns = append(columns, `CAST(SUM(job.num_acc) as int) as totalAccs`)
	} else {
		columns = append(columns, "0 as totalAccs")
	}

	if need("totalAccHours") {
		columns = append(columns, fmt.Sprintf(`CAST(ROUND(SUM(%s * job.num_acc) / 3600) as int) as totalAccHours`, durationExpr))
	} else {
		columns = append(columns, "0 as totalAccHours")
	}

	if need("runningJobs") {
		columns = append(columns, `COUNT(CASE WHEN job.job_state = 'running' THEN 1 END) as runningJobs`)
	} else {
		columns = append(columns, "0 as runningJobs")
	}

	if need("shortJobs") {
		columns = append(columns, fmt.Sprintf(`COUNT(CASE WHEN job.duration < %d THEN 1 END) as shortJobs`, shortThreshold))
	} else {
		columns = append(columns, "0 as shortJobs")
	}

	query := sq.Select(columns...).From("job")
	if col != "" {
		query = query.GroupBy(col)
	}

	for _, f := range filter {
		query = BuildWhereClause(f, query)
	}

	return query
}

// JobsStatsGrouped computes job statistics grouped by a dimension (user, project, cluster, or subcluster).
// Only columns listed in reqFields are computed; others return 0. User display names are looked up
// in a separate lightweight query to avoid JOIN overhead on the main aggregation.
func (r *JobRepository) JobsStatsGrouped(
	ctx context.Context,
	filter []*model.JobFilter,
	page *model.PageRequest,
	sortBy *model.SortByAggregate,
	groupBy *model.Aggregate,
	reqFields map[string]bool,
) ([]*model.JobsStatistics, error) {
	col := groupBy2column[*groupBy]
	query := r.buildStatsQuery(filter, col, config.Keys.ShortRunningJobsDuration, reqFields)

	query, err := SecurityCheck(ctx, query)
	if err != nil {
		return nil, err
	}

	if sortBy != nil {
		sortBy := sortBy2column[*sortBy]
		query = query.OrderBy(fmt.Sprintf("%s DESC", sortBy))
	}
	if page != nil && page.ItemsPerPage != -1 {
		limit := uint64(page.ItemsPerPage)
		query = query.Offset((uint64(page.Page) - 1) * limit).Limit(limit)
	}

	rows, err := query.RunWith(r.DB).QueryContext(ctx)
	if err != nil {
		cclog.Warn("Error while querying DB for job statistics")
		return nil, err
	}
	defer rows.Close()

	stats := make([]*model.JobsStatistics, 0, 100)

	for rows.Next() {
		var id sql.NullString
		var jobs, users, walltime, nodes, nodeHours, cores, coreHours, accs, accHours, runningJobs, shortJobs sql.NullInt64
		if err := rows.Scan(&id, &jobs, &users, &walltime, &nodes, &nodeHours, &cores, &coreHours, &accs, &accHours, &runningJobs, &shortJobs); err != nil {
			cclog.Warnf("Error while scanning rows: %s", err.Error())
			return nil, err
		}

		if id.Valid {
			stats = append(stats,
				&model.JobsStatistics{
					ID:             id.String,
					TotalJobs:      int(jobs.Int64),
					TotalUsers:     int(users.Int64),
					TotalWalltime:  int(walltime.Int64),
					TotalNodes:     int(nodes.Int64),
					TotalNodeHours: int(nodeHours.Int64),
					TotalCores:     int(cores.Int64),
					TotalCoreHours: int(coreHours.Int64),
					TotalAccs:      int(accs.Int64),
					TotalAccHours:  int(accHours.Int64),
					RunningJobs:    int(runningJobs.Int64),
					ShortJobs:      int(shortJobs.Int64),
				})
		}
	}

	if err := rows.Err(); err != nil {
		return nil, err
	}

	// Post-query name lookup for user grouping (avoids LEFT JOIN on aggregation query)
	if col == "job.hpc_user" && len(stats) > 0 {
		usernames := make([]any, len(stats))
		for i, s := range stats {
			usernames[i] = s.ID
		}

		nameQuery := sq.Select("username", "name").From("hpc_user").Where(sq.Eq{"username": usernames})
		nameRows, err := nameQuery.RunWith(r.DB).QueryContext(ctx)
		if err != nil {
			cclog.Warnf("Error looking up user names: %s", err.Error())
			// Non-fatal: stats are still valid without display names
		} else {
			defer nameRows.Close()
			nameMap := make(map[string]string, len(stats))
			for nameRows.Next() {
				var username, name string
				if err := nameRows.Scan(&username, &name); err == nil {
					nameMap[username] = name
				}
			}
			for _, s := range stats {
				if name, ok := nameMap[s.ID]; ok {
					s.Name = name
				}
			}
		}
	}

	return stats, nil
}

// JobsStats computes overall job statistics across all matching jobs without grouping.
//
// This method provides a single aggregate view of job metrics, useful for dashboard
// summaries and overall system utilization reports.
//
// Parameters:
//   - ctx: Context for security checks and cancellation
//   - filter: Filters to apply (time range, cluster, job state, etc.)
//
// Returns a single-element slice containing aggregate statistics:
//   - totalJobs, totalUsers, totalWalltime
//   - totalNodeHours, totalCoreHours, totalAccHours
//
// Unlike JobsStatsGrouped, this returns overall totals without breaking down by dimension.
// Security checks are applied via SecurityCheck to respect user access levels.
func (r *JobRepository) JobsStats(
	ctx context.Context,
	filter []*model.JobFilter,
	reqFields map[string]bool,
) ([]*model.JobsStatistics, error) {
	start := time.Now()
	query := r.buildStatsQuery(filter, "", config.Keys.ShortRunningJobsDuration, reqFields)
	query, err := SecurityCheck(ctx, query)
	if err != nil {
		return nil, err
	}

	row := query.RunWith(r.DB).QueryRowContext(ctx)
	stats := make([]*model.JobsStatistics, 0, 1)

	var jobs, users, walltime, nodes, nodeHours, cores, coreHours, accs, accHours, runningJobs, shortJobs sql.NullInt64
	if err := row.Scan(&jobs, &users, &walltime, &nodes, &nodeHours, &cores, &coreHours, &accs, &accHours, &runningJobs, &shortJobs); err != nil {
		cclog.Warn("Error while scanning rows")
		return nil, err
	}

	if jobs.Valid {
		var totalNodeHours, totalCoreHours, totalAccHours int

		if nodeHours.Valid {
			totalNodeHours = int(nodeHours.Int64)
		}
		if coreHours.Valid {
			totalCoreHours = int(coreHours.Int64)
		}
		if accHours.Valid {
			totalAccHours = int(accHours.Int64)
		}
		stats = append(stats,
			&model.JobsStatistics{
				TotalJobs:      int(jobs.Int64),
				TotalUsers:     int(users.Int64),
				TotalWalltime:  int(walltime.Int64),
				TotalNodeHours: totalNodeHours,
				TotalCoreHours: totalCoreHours,
				TotalAccHours:  totalAccHours,
				RunningJobs:    int(runningJobs.Int64),
				ShortJobs:      int(shortJobs.Int64),
			})
	}

	cclog.Debugf("Timer JobStats %s", time.Since(start))
	return stats, nil
}

// LoadJobStat retrieves a specific statistic for a metric from a job's statistics.
// Returns 0.0 if the metric is not found or statType is invalid.
//
// Parameters:
//   - job: Job struct with populated Statistics field
//   - metric: Name of the metric to query (e.g., "cpu_load", "mem_used")
//   - statType: Type of statistic: "avg", "min", or "max"
//
// Returns the requested statistic value or 0.0 if not found.
func LoadJobStat(job *schema.Job, metric string, statType string) float64 {
	if stats, ok := job.Statistics[metric]; ok {
		switch statType {
		case "avg":
			return stats.Avg
		case "max":
			return stats.Max
		case "min":
			return stats.Min
		default:
			cclog.Errorf("Unknown stat type %s", statType)
		}
	}

	return 0.0
}

// JobCountGrouped counts jobs grouped by a dimension without computing detailed statistics.
//
// This is a lightweight alternative to JobsStatsGrouped when only job counts are needed,
// avoiding the overhead of calculating walltime and resource usage metrics.
//
// Parameters:
//   - ctx: Context for security checks
//   - filter: Filters to apply
//   - groupBy: Grouping dimension (User, Project, Cluster, or SubCluster)
//
// Returns JobsStatistics with only ID and TotalJobs populated for each group.
func (r *JobRepository) JobCountGrouped(
	ctx context.Context,
	filter []*model.JobFilter,
	groupBy *model.Aggregate,
) ([]*model.JobsStatistics, error) {
	start := time.Now()
	col := groupBy2column[*groupBy]
	query := r.buildCountQuery(filter, "", col)
	query, err := SecurityCheck(ctx, query)
	if err != nil {
		return nil, err
	}
	rows, err := query.RunWith(r.DB).QueryContext(ctx)
	if err != nil {
		cclog.Warn("Error while querying DB for job statistics")
		return nil, err
	}
	defer rows.Close()

	stats := make([]*model.JobsStatistics, 0, 100)

	for rows.Next() {
		var id sql.NullString
		var cnt sql.NullInt64
		if err := rows.Scan(&id, &cnt); err != nil {
			cclog.Warn("Error while scanning rows")
			return nil, err
		}
		if id.Valid {
			stats = append(stats,
				&model.JobsStatistics{
					ID:        id.String,
					TotalJobs: int(cnt.Int64),
				})
		}
	}

	if err := rows.Err(); err != nil {
		return nil, err
	}

	cclog.Debugf("Timer JobCountGrouped %s", time.Since(start))
	return stats, nil
}

// AddJobCountGrouped augments existing statistics with additional job counts by category.
//
// This method enriches JobsStatistics returned by JobsStatsGrouped or JobCountGrouped
// with counts of running or short-running (based on ShortRunningJobsDuration) jobs, matched by group ID.
//
// Parameters:
//   - ctx: Context for security checks
//   - filter: Filters to apply
//   - groupBy: Grouping dimension (must match the dimension used for stats parameter)
//   - stats: Existing statistics to augment (modified in-place by ID matching)
//   - kind: "running" to add RunningJobs count, "short" to add ShortJobs count
//
// Returns the same stats slice with RunningJobs or ShortJobs fields populated per group.
// Groups without matching jobs will have 0 for the added field.
func (r *JobRepository) AddJobCountGrouped(
	ctx context.Context,
	filter []*model.JobFilter,
	groupBy *model.Aggregate,
	stats []*model.JobsStatistics,
	kind string,
) ([]*model.JobsStatistics, error) {
	start := time.Now()
	col := groupBy2column[*groupBy]
	query := r.buildCountQuery(filter, kind, col)
	query, err := SecurityCheck(ctx, query)
	if err != nil {
		return nil, err
	}
	rows, err := query.RunWith(r.DB).QueryContext(ctx)
	if err != nil {
		cclog.Warn("Error while querying DB for job statistics")
		return nil, err
	}
	defer rows.Close()

	counts := make(map[string]int)

	for rows.Next() {
		var id sql.NullString
		var cnt sql.NullInt64
		if err := rows.Scan(&id, &cnt); err != nil {
			cclog.Warn("Error while scanning rows")
			return nil, err
		}
		if id.Valid {
			counts[id.String] = int(cnt.Int64)
		}
	}

	if err := rows.Err(); err != nil {
		return nil, err
	}

	switch kind {
	case "running":
		for _, s := range stats {
			s.RunningJobs = counts[s.ID]
		}
	case "short":
		for _, s := range stats {
			s.ShortJobs = counts[s.ID]
		}
	}

	cclog.Debugf("Timer AddJobCountGrouped %s", time.Since(start))
	return stats, nil
}

// AddJobCount augments existing overall statistics with additional job counts by category.
//
// Similar to AddJobCountGrouped but for ungrouped statistics. Applies the same count
// to all statistics entries (typically just one).
//
// Parameters:
//   - ctx: Context for security checks
//   - filter: Filters to apply
//   - stats: Existing statistics to augment (modified in-place)
//   - kind: "running" to add RunningJobs count, "short" to add ShortJobs count
//
// Returns the same stats slice with RunningJobs or ShortJobs fields set to the total count.
func (r *JobRepository) AddJobCount(
	ctx context.Context,
	filter []*model.JobFilter,
	stats []*model.JobsStatistics,
	kind string,
) ([]*model.JobsStatistics, error) {
	start := time.Now()
	query := r.buildCountQuery(filter, kind, "")
	query, err := SecurityCheck(ctx, query)
	if err != nil {
		return nil, err
	}
	var cnt sql.NullInt64
	if err := query.RunWith(r.DB).QueryRowContext(ctx).Scan(&cnt); err != nil {
		cclog.Warn("Error while querying DB for job count")
		return nil, err
	}

	count := int(cnt.Int64)

	switch kind {
	case "running":
		for _, s := range stats {
			s.RunningJobs = count
		}
	case "short":
		for _, s := range stats {
			s.ShortJobs = count
		}
	}

	cclog.Debugf("Timer AddJobCount %s", time.Since(start))
	return stats, nil
}

// AddHistograms augments statistics with distribution histograms for job properties.
//
// Generates histogram data for visualization of job duration, node count, core count,
// and accelerator count distributions. Duration histogram uses intelligent binning based
// on the requested resolution.
//
// Parameters:
//   - ctx: Context for security checks
//   - filter: Filters to apply to jobs included in histograms
//   - stat: Statistics struct to augment (modified in-place)
//   - durationBins: Bin size - "1m", "10m", "1h", "6h", "12h", or "24h" (default)
//
// Populates these fields in stat:
//   - HistDuration: Job duration distribution (zero-padded bins)
//   - HistNumNodes: Node count distribution
//   - HistNumCores: Core (hwthread) count distribution
//   - HistNumAccs: Accelerator count distribution
//
// Duration bins are pre-initialized with zeros to ensure consistent ranges for visualization.
// Bin size determines both the width and maximum duration displayed (e.g., "1h" = 48 bins × 1h = 48h max).
func (r *JobRepository) AddHistograms(
	ctx context.Context,
	filter []*model.JobFilter,
	stat *model.JobsStatistics,
	durationBins *string,
) (*model.JobsStatistics, error) {
	start := time.Now()

	var targetBinCount int
	var targetBinSize int
	switch *durationBins {
	case "1m": // 1 Minute Bins + Max 60 Bins -> Max 60 Minutes
		targetBinCount = 60
		targetBinSize = 60
	case "10m": // 10 Minute Bins + Max 72 Bins -> Max 12 Hours
		targetBinCount = 72
		targetBinSize = 600
	case "1h": // 1 Hour Bins + Max 48 Bins -> Max 48 Hours
		targetBinCount = 48
		targetBinSize = 3600
	case "6h": // 6 Hour Bins + Max 12 Bins -> Max 3 Days
		targetBinCount = 12
		targetBinSize = 21600
	case "12h": // 12 hour Bins + Max 14 Bins -> Max 7 Days
		targetBinCount = 14
		targetBinSize = 43200
	default: // 24h
		targetBinCount = 24
		targetBinSize = 3600
	}

	var err error
	// Return X-Values always as seconds, will be formatted into minutes and hours in frontend
	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)
	stat.HistDuration, err = r.jobsDurationStatisticsHistogram(ctx, value, filter, targetBinSize, &targetBinCount)
	if err != nil {
		cclog.Warn("Error while loading job statistics histogram: job duration")
		return nil, err
	}

	stat.HistNumNodes, err = r.jobsStatisticsHistogram(ctx, "job.num_nodes as value", filter)
	if err != nil {
		cclog.Warn("Error while loading job statistics histogram: num nodes")
		return nil, err
	}

	stat.HistNumCores, err = r.jobsStatisticsHistogram(ctx, "job.num_hwthreads as value", filter)
	if err != nil {
		cclog.Warn("Error while loading job statistics histogram: num hwthreads")
		return nil, err
	}

	stat.HistNumAccs, err = r.jobsStatisticsHistogram(ctx, "job.num_acc as value", filter)
	if err != nil {
		cclog.Warn("Error while loading job statistics histogram: num acc")
		return nil, err
	}

	cclog.Debugf("Timer AddHistograms %s", time.Since(start))
	return stat, nil
}

// AddMetricHistograms augments statistics with distribution histograms for job metrics.
//
// Generates histogram data for metrics like CPU load, memory usage, etc. Handles running
// and completed jobs differently: running jobs load data from metric backend, completed jobs
// use footprint data from database.
//
// Parameters:
//   - ctx: Context for security checks
//   - filter: Filters to apply (MUST contain State filter for running jobs)
//   - metrics: List of metric names to histogram (e.g., ["cpu_load", "mem_used"])
//   - stat: Statistics struct to augment (modified in-place)
//   - targetBinCount: Number of histogram bins (default: 10)
//
// Populates HistMetrics field in stat with MetricHistoPoints for each metric.
//
// Binning algorithm:
//   - Values normalized to metric's peak value from cluster configuration
//   - Bins evenly distributed from 0 to peak
//   - Pre-initialized with zeros for consistent visualization
//
// Limitations:
//   - Running jobs: Limited to 5000 jobs for performance
//   - Requires valid cluster configuration with metric peak values
//   - Uses footprint statistic (avg/max/min) configured per metric
func (r *JobRepository) AddMetricHistograms(
	ctx context.Context,
	filter []*model.JobFilter,
	metrics []string,
	stat *model.JobsStatistics,
	targetBinCount *int,
) (*model.JobsStatistics, error) {
	start := time.Now()

	// Running Jobs Only: First query jobdata from sqlite, then query data and make bins
	for _, f := range filter {
		if f.State != nil {
			if len(f.State) == 1 && f.State[0] == "running" {
				stat.HistMetrics = r.runningJobsMetricStatisticsHistogram(ctx, metrics, filter, targetBinCount)
				cclog.Debugf("Timer AddMetricHistograms %s", time.Since(start))
				return stat, nil
			}
		}
	}

	// All other cases: Query and make bins in sqlite directly
	for _, m := range metrics {
		metricHisto, err := r.jobsMetricStatisticsHistogram(ctx, m, filter, targetBinCount)
		if err != nil {
			cclog.Warnf("Error while loading job metric statistics histogram: %s", m)
			continue
		}
		stat.HistMetrics = append(stat.HistMetrics, metricHisto)
	}

	cclog.Debugf("Timer AddMetricHistograms %s", time.Since(start))
	return stat, nil
}

// jobsStatisticsHistogram generates a simple histogram by grouping on a column value.
//
// Used for histograms where the column value directly represents the bin (e.g., node count, core count).
// Unlike duration/metric histograms, this doesn't pre-initialize bins with zeros.
//
// Parameters:
//   - value: SQL expression that produces the histogram value, aliased as "value"
//   - filters: Job filters to apply
//
// Returns histogram points with Value (from column) and Count (number of jobs).
func (r *JobRepository) jobsStatisticsHistogram(
	ctx context.Context,
	value string,
	filters []*model.JobFilter,
) ([]*model.HistoPoint, error) {
	start := time.Now()
	query, qerr := SecurityCheck(ctx,
		sq.Select(value, "COUNT(*) AS count").From("job"))

	if qerr != nil {
		return nil, qerr
	}

	for _, f := range filters {
		query = BuildWhereClause(f, query)
	}

	rows, err := query.GroupBy("value").RunWith(r.DB).QueryContext(ctx)
	if err != nil {
		cclog.Error("Error while running query")
		return nil, err
	}
	defer rows.Close()

	points := make([]*model.HistoPoint, 0)
	// is it possible to introduce zero values here? requires info about bincount
	for rows.Next() {
		point := model.HistoPoint{}
		if err := rows.Scan(&point.Value, &point.Count); err != nil {
			cclog.Warn("Error while scanning rows")
			return nil, err
		}

		points = append(points, &point)
	}

	if err := rows.Err(); err != nil {
		return nil, err
	}

	cclog.Debugf("Timer jobsStatisticsHistogram %s", time.Since(start))
	return points, nil
}

// jobsDurationStatisticsHistogram generates a duration histogram with pre-initialized bins.
//
// Bins are zero-padded to provide consistent ranges for visualization, unlike simple
// histograms which only return bins with data. The value parameter should compute
// the bin number from job duration.
//
// Parameters:
//   - value: SQL expression computing bin number from duration, aliased as "value"
//   - filters: Job filters to apply
//   - binSizeSeconds: Width of each bin in seconds
//   - targetBinCount: Number of bins to pre-initialize
//
// Returns histogram points with Value (bin_number × binSizeSeconds) and Count.
// All bins from 1 to targetBinCount are returned, with Count=0 for empty bins.
//
// Algorithm:
//  1. Pre-initialize targetBinCount bins with zero counts
//  2. Query database for actual counts per bin
//  3. Match query results to pre-initialized bins by value
//  4. Bins without matches remain at zero
func (r *JobRepository) jobsDurationStatisticsHistogram(
	ctx context.Context,
	value string,
	filters []*model.JobFilter,
	binSizeSeconds int,
	targetBinCount *int,
) ([]*model.HistoPoint, error) {
	start := time.Now()
	query, qerr := SecurityCheck(ctx,
		sq.Select(value, "COUNT(*) AS count").From("job"))

	if qerr != nil {
		return nil, qerr
	}

	// Each bin represents a duration range: bin N = [N*binSizeSeconds, (N+1)*binSizeSeconds)
	// Example: binSizeSeconds=3600 (1 hour), bin 1 = 0-1h, bin 2 = 1-2h, etc.
	points := make([]*model.HistoPoint, 0, *targetBinCount)
	for i := 1; i <= *targetBinCount; i++ {
		point := model.HistoPoint{Value: i * binSizeSeconds, Count: 0}
		points = append(points, &point)
	}

	// Build a map from bin value (seconds) to slice index for O(1) lookup.
	binMap := make(map[int]int, len(points))
	for i, p := range points {
		binMap[p.Value] = i
	}

	for _, f := range filters {
		query = BuildWhereClause(f, query)
	}

	rows, err := query.GroupBy("value").RunWith(r.DB).QueryContext(ctx)
	if err != nil {
		cclog.Error("Error while running query")
		return nil, err
	}
	defer rows.Close()

	// Match query results to pre-initialized bins using map lookup.
	// point.Value from query is the bin number; multiply by binSizeSeconds to get bin key.
	for rows.Next() {
		point := model.HistoPoint{}
		if err := rows.Scan(&point.Value, &point.Count); err != nil {
			cclog.Warn("Error while scanning rows")
			return nil, err
		}

		if idx, ok := binMap[point.Value*binSizeSeconds]; ok {
			points[idx].Count = point.Count
		}
	}

	if err := rows.Err(); err != nil {
		return nil, err
	}

	cclog.Debugf("Timer jobsStatisticsHistogram %s", time.Since(start))
	return points, nil
}

// jobsMetricStatisticsHistogram generates a metric histogram using footprint data from completed jobs.
//
// Values are normalized to the metric's peak value and distributed into bins. The algorithm
// is based on SQL histogram generation techniques, extracting metric values from JSON footprint
// and computing bin assignments in SQL.
//
// Parameters:
//   - metric: Metric name (e.g., "cpu_load", "mem_used")
//   - filters: Job filters to apply
//   - bins: Number of bins to generate
//
// Returns MetricHistoPoints with metric name, unit, footprint stat type, and binned data.
//
// Algorithm:
//  1. Determine peak value from cluster configuration (filtered cluster or max across all)
//  2. Generate SQL that extracts footprint value, normalizes to [0,1], multiplies by bin count
//  3. Pre-initialize bins with min/max ranges based on peak value
//  4. Query database for counts per bin
//  5. Match results to pre-initialized bins
//
// Special handling: Values exactly equal to peak are forced into the last bin by multiplying
// peak by 0.999999999 to avoid creating an extra bin.
func (r *JobRepository) jobsMetricStatisticsHistogram(
	ctx context.Context,
	metric string,
	filters []*model.JobFilter,
	bins *int,
) (*model.MetricHistoPoints, error) {
	// Peak value defines the upper bound for binning: values are distributed across
	// bins from 0 to peak. First try to get peak from filtered cluster, otherwise
	// scan all clusters to find the maximum peak value.
	var metricConfig *schema.MetricConfig
	var peak float64
	var unit string
	var footprintStat string

	// Try to get metric config from filtered cluster
	for _, f := range filters {
		if f.Cluster != nil {
			metricConfig = archive.GetMetricConfig(*f.Cluster.Eq, metric)
			peak = metricConfig.Peak
			unit = metricConfig.Unit.Prefix + metricConfig.Unit.Base
			footprintStat = metricConfig.Footprint
			cclog.Debugf("Cluster %s filter found with peak %f for %s", *f.Cluster.Eq, peak, metric)
		}
	}

	// If no cluster filter or peak not found, find largest peak across all clusters
	// This ensures histogram can accommodate all possible values
	if peak == 0.0 {
		for _, c := range archive.Clusters {
			for _, m := range c.MetricConfig {
				if m.Name == metric {
					if m.Peak > peak {
						peak = m.Peak
					}
					if unit == "" {
						unit = m.Unit.Prefix + m.Unit.Base
					}
					if footprintStat == "" {
						footprintStat = m.Footprint
					}
				}
			}
		}
	}

	// Construct SQL histogram bins using normalized values.
	// Algorithm based on: https://jereze.com/code/sql-histogram/ (modified)
	start := time.Now()

	// Bin calculation formula:
	//   bin_number = CAST( (value / peak) * num_bins AS INTEGER ) + 1
	// Special case: value == peak would create bin N+1, so we test for equality
	// and multiply peak by 0.999999999 to force it into bin N.
	binQuery := fmt.Sprintf(`CAST(
		((case when json_extract(footprint, "$.%s") = %f then %f*0.999999999 else json_extract(footprint, "$.%s") end) / %f)
		* %v as INTEGER )`,
		(metric + "_" + footprintStat), peak, peak, (metric + "_" + footprintStat), peak, *bins)

	mainQuery := sq.Select(
		fmt.Sprintf(`%s + 1 as bin`, binQuery),
		`count(*) as count`,
	).From("job").Where(
		"JSON_VALID(footprint)",
	).Where(fmt.Sprintf(`json_extract(footprint, "$.%s") is not null and json_extract(footprint, "$.%s") <= %f`, (metric + "_" + footprintStat), (metric + "_" + footprintStat), peak))

	mainQuery, qerr := SecurityCheck(ctx, mainQuery)
	if qerr != nil {
		return nil, qerr
	}

	for _, f := range filters {
		mainQuery = BuildWhereClause(f, mainQuery)
	}

	mainQuery = mainQuery.GroupBy("bin").OrderBy("bin")

	rows, err := mainQuery.RunWith(r.DB).QueryContext(ctx)
	if err != nil {
		cclog.Errorf("Error while running mainQuery: %s", err)
		return nil, err
	}
	defer rows.Close()

	// Pre-initialize bins with calculated min/max ranges.
	// Example: peak=1000, bins=10 -> bin 1=[0,100), bin 2=[100,200), ..., bin 10=[900,1000]
	points := make([]*model.MetricHistoPoint, 0, *bins)
	binStep := int(peak) / *bins
	for i := 1; i <= *bins; i++ {
		binMin := (binStep * (i - 1))
		binMax := (binStep * i)
		idx := i
		epoint := model.MetricHistoPoint{Bin: &idx, Count: 0, Min: &binMin, Max: &binMax}
		points = append(points, &epoint)
	}

	// Build a map from bin number to slice index for O(1) lookup.
	binMap := make(map[int]int, len(points))
	for i, p := range points {
		if p.Bin != nil {
			binMap[*p.Bin] = i
		}
	}

	// Match query results to pre-initialized bins using map lookup.
	for rows.Next() {
		rpoint := model.MetricHistoPoint{}
		if err := rows.Scan(&rpoint.Bin, &rpoint.Count); err != nil {
			cclog.Warnf("Error while scanning rows for %s", metric)
			return nil, err
		}

		if rpoint.Bin != nil {
			if idx, ok := binMap[*rpoint.Bin]; ok {
				points[idx].Count = rpoint.Count
			}
		}
	}

	if err := rows.Err(); err != nil {
		return nil, err
	}

	result := model.MetricHistoPoints{Metric: metric, Unit: unit, Stat: &footprintStat, Data: points}

	cclog.Debugf("Timer jobsStatisticsHistogram %s", time.Since(start))
	return &result, nil
}

// runningJobsMetricStatisticsHistogram generates metric histograms for running jobs using live data.
//
// Unlike completed jobs which use footprint data from the database, running jobs require
// fetching current metric averages from the metric backend (via metricdispatch).
//
// Parameters:
//   - metrics: List of metric names
//   - filters: Job filters (should filter to running jobs only)
//   - bins: Number of histogram bins
//
// Returns slice of MetricHistoPoints, one per metric.
//
// Limitations:
//   - Maximum 5000 jobs (returns nil if more jobs match)
//   - Requires metric backend availability
//   - Bins based on metric peak values from cluster configuration
//
// Algorithm:
//  1. Query first 5001 jobs to check count limit
//  2. Load metric averages for all jobs via metricdispatch
//  3. For each metric, create bins based on peak value
//  4. Iterate averages and count jobs per bin
func (r *JobRepository) runningJobsMetricStatisticsHistogram(
	ctx context.Context,
	metrics []string,
	filters []*model.JobFilter,
	bins *int,
) []*model.MetricHistoPoints {
	// Get Jobs
	jobs, err := r.QueryJobs(ctx, filters, &model.PageRequest{Page: 1, ItemsPerPage: 5000 + 1}, nil)
	if err != nil {
		cclog.Errorf("Error while querying jobs for footprint: %s", err)
		return nil
	}
	if len(jobs) > 5000 {
		cclog.Errorf("too many jobs matched (max: %d)", 5000)
		return nil
	}

	// Get AVGs from metric repo
	avgs := make([][]schema.Float, len(metrics))
	for i := range avgs {
		avgs[i] = make([]schema.Float, 0, len(jobs))
	}

	for _, job := range jobs {
		if job.MonitoringStatus == schema.MonitoringStatusDisabled || job.MonitoringStatus == schema.MonitoringStatusArchivingFailed {
			continue
		}

		if err := metricdispatch.LoadAverages(job, metrics, avgs, ctx); err != nil {
			cclog.Errorf("Error while loading averages for histogram: %s", err)
			return nil
		}
	}

	// Iterate metrics to fill endresult
	data := make([]*model.MetricHistoPoints, 0)
	for idx, metric := range metrics {
		// Get specific Peak or largest Peak
		var metricConfig *schema.MetricConfig
		var peak float64
		var unit string

		for _, f := range filters {
			if f.Cluster != nil {
				metricConfig = archive.GetMetricConfig(*f.Cluster.Eq, metric)
				peak = metricConfig.Peak
				unit = metricConfig.Unit.Prefix + metricConfig.Unit.Base
			}
		}

		if peak == 0.0 {
			for _, c := range archive.Clusters {
				for _, m := range c.MetricConfig {
					if m.Name == metric {
						if m.Peak > peak {
							peak = m.Peak
						}
						if unit == "" {
							unit = m.Unit.Prefix + m.Unit.Base
						}
					}
				}
			}
		}

		// Make and fill bins
		peakBin := int(peak) / *bins

		points := make([]*model.MetricHistoPoint, 0)
		for b := 0; b < *bins; b++ {
			count := 0
			bindex := b + 1
			bmin := peakBin * b
			bmax := peakBin * (b + 1)

			// Iterate AVG values for indexed metric and count for bins
			for _, val := range avgs[idx] {
				if int(val) >= bmin && int(val) < bmax {
					count += 1
				}
			}

			// Append Bin to Metric Result Array
			point := model.MetricHistoPoint{Bin: &bindex, Count: count, Min: &bmin, Max: &bmax}
			points = append(points, &point)
		}

		// Append Metric Result Array to final results array
		result := model.MetricHistoPoints{Metric: metric, Unit: unit, Data: points}
		data = append(data, &result)
	}

	return data
}