The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
feat: otel profiling and ui improvements (#243)
narrow-adventure2c76cf487b31
diff --git a/backend/app/controllers/clientcontrollers/profile_ingest_controller_test.go b/backend/app/controllers/clientcontrollers/profile_ingest_controller_test.goindex a9a09317..69dd5680 100644--- a/backend/app/controllers/clientcontrollers/profile_ingest_controller_test.go+++ b/backend/app/controllers/clientcontrollers/profile_ingest_controller_test.go@@ -38,14 +38,16 @@ func setupProfilingDB(t *testing.T) {last_seen DATETIME NOT NULL, UNIQUE(project_id, service_name, stack_hash))`,`CREATE TABLE profiling_samples (project_id TEXT NOT NULL, profile_id TEXT NOT NULL, service_name TEXT NOT NULL DEFAULT '',- type TEXT NOT NULL DEFAULT '', start_time DATETIME NOT NULL, end_time DATETIME NOT NULL,+ type TEXT NOT NULL DEFAULT '', unit TEXT NOT NULL DEFAULT '', is_gauge INTEGER NOT NULL DEFAULT 0,+ start_time DATETIME NOT NULL, end_time DATETIME NOT NULL,stack_hash INTEGER NOT NULL, value INTEGER NOT NULL DEFAULT 0, labels TEXT NOT NULL DEFAULT '{}',server_name TEXT NOT NULL DEFAULT '', app_version TEXT NOT NULL DEFAULT '',trace_id TEXT NOT NULL DEFAULT '', span_id TEXT NOT NULL DEFAULT '')`,`CREATE TABLE profiles (id TEXT NOT NULL, project_id TEXT NOT NULL, recorded_at DATETIME NOT NULL,duration INTEGER NOT NULL DEFAULT 0, service_name TEXT NOT NULL DEFAULT '',- profile_type TEXT NOT NULL DEFAULT '', sample_count INTEGER NOT NULL DEFAULT 0,+ profile_type TEXT NOT NULL DEFAULT '', unit TEXT NOT NULL DEFAULT '', is_gauge INTEGER NOT NULL DEFAULT 0,+ sample_count INTEGER NOT NULL DEFAULT 0,total_value INTEGER NOT NULL DEFAULT 0, server_name TEXT NOT NULL DEFAULT '',app_version TEXT NOT NULL DEFAULT '', attributes TEXT NOT NULL DEFAULT '{}',storage_key TEXT NOT NULL DEFAULT '', trace_id TEXT NOT NULL DEFAULT '',@@ -126,11 +128,11 @@ func TestProfileIngest_StoresExplodedRows(t *testing.T) {if stacks != 2 {t.Errorf("profiling_stacks = %d, want 2", stacks)}- if samples != 2 {- t.Errorf("profiling_samples = %d, want 2", samples)+ if samples != 4 {+ t.Errorf("profiling_samples = %d, want 4 (samples + cpu types, 2 stacks each)", samples)}- if profiles != 1 {- t.Errorf("profiles = %d, want 1 (cpu only)", profiles)+ if profiles != 2 {+ t.Errorf("profiles = %d, want 2 (one metadata row per sample type: samples + cpu)", profiles)}var service, server, version stringdiff --git a/backend/app/controllers/profile.controller.go b/backend/app/controllers/profile.controller.goindex fa1c8229..234dddc1 100644--- a/backend/app/controllers/profile.controller.go+++ b/backend/app/controllers/profile.controller.go@@ -3,10 +3,12 @@ package controllersimport ("net/http""slices"+ "strings""time""unicode/utf8""github.com/gin-gonic/gin"+ "github.com/google/uuid""github.com/tracewayapp/traceway/backend/app/cache""github.com/tracewayapp/traceway/backend/app/middleware""github.com/tracewayapp/traceway/backend/app/models"@@ -23,15 +25,43 @@ type ProfileGroupedRequest struct {ToDate time.Time `json:"toDate"`OrderBy string `json:"orderBy"`SortDirection string `json:"sortDirection"`+ Search string `json:"search"`Pagination PaginationParams `json:"pagination"`}type ProfileSeriesRequest struct {- FromDate time.Time `json:"fromDate"`- ToDate time.Time `json:"toDate"`- ServiceName string `json:"serviceName"`- Type string `json:"type"`- IntervalMinutes int `json:"intervalMinutes"`+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ ServiceName string `json:"serviceName"`+ Type string `json:"type"`+ IsGauge bool `json:"isGauge"`+ IntervalMinutes int `json:"intervalMinutes"`+ Labels map[string]string `json:"labels"`+ AppVersion string `json:"appVersion"`+ ServerName string `json:"serverName"`+ Normalize bool `json:"normalize"`+}++type ProfileSeriesBreakdownRequest struct {+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ ServiceName string `json:"serviceName"`+ Type string `json:"type"`+ IsGauge bool `json:"isGauge"`+ IntervalMinutes int `json:"intervalMinutes"`+ Labels map[string]string `json:"labels"`+ AppVersion string `json:"appVersion"`+ ServerName string `json:"serverName"`+ Normalize bool `json:"normalize"`+ Dimension string `json:"dimension"`+ Limit int `json:"limit"`+}++type ProfileDimensionsRequest struct {+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ ServiceName string `json:"serviceName"`+ Type string `json:"type"`}type ProfileFlameGraphRequest struct {@@ -39,7 +69,29 @@ type ProfileFlameGraphRequest struct {ToDate time.Time `json:"toDate"`ServiceName string `json:"serviceName"`Type string `json:"type"`+ Unit string `json:"unit"`+ IsGauge bool `json:"isGauge"`Labels map[string]string `json:"labels"`+ AppVersion string `json:"appVersion"`+ ServerName string `json:"serverName"`+}++type ProfileTypesRequest struct {+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ ServiceName string `json:"serviceName"`+}++type ProfileTopFunctionsRequest struct {+ FromDate time.Time `json:"fromDate"`+ ToDate time.Time `json:"toDate"`+ ServiceName string `json:"serviceName"`+ Type string `json:"type"`+ IsGauge bool `json:"isGauge"`+ Labels map[string]string `json:"labels"`+ Limit int `json:"limit"`+ AppVersion string `json:"appVersion"`+ ServerName string `json:"serverName"`}type ProfileLabelsRequest struct {@@ -54,6 +106,11 @@ type ProfileSeriesPoint struct {Value float64 `json:"value"`}+type ProfileSeriesGroupResponse struct {+ Key string `json:"key"`+ Points []ProfileSeriesPoint `json:"points"`+}+func (p profileController) FindGroupedByService(c *gin.Context) {projectId, err := middleware.GetProjectId(c)if err != nil {@@ -67,7 +124,12 @@ func (p profileController) FindGroupedByService(c *gin.Context) {return}- groups, total, err := repositories.ProfileRepository.FindGroupedByService(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection)+ search := strings.TrimSpace(request.Search)+ if utf8.RuneCountInString(search) > 200 {+ search = ""+ }++ groups, total, err := repositories.ProfileRepository.FindGroupedByService(c, projectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.SortDirection, search)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error loading grouped profiles: %w", err))return@@ -100,8 +162,14 @@ func (p profileController) GetSeries(c *gin.Context) {c.JSON(http.StatusBadRequest, gin.H{"error": "serviceName and type are required"})return}+ if !validateProfileLabelFilters(c, projectId, request.Labels) {+ return+ }+ if !validateProfileCohort(c, request.AppVersion, request.ServerName) {+ return+ }- points, err := repositories.ProfileRepository.GetSeries(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.IntervalMinutes)+ points, err := repositories.ProfileRepository.GetSeries(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.IntervalMinutes, request.IsGauge, request.Labels, request.AppVersion, request.ServerName, request.Normalize)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error loading profile series: %w", err))return@@ -114,6 +182,42 @@ func (p profileController) GetSeries(c *gin.Context) {c.JSON(http.StatusOK, out)}+func (p profileController) DiscoverTypes(c *gin.Context) {+ projectId, err := middleware.GetProjectId(c)+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ var request ProfileTypesRequest+ if err := c.ShouldBindJSON(&request); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }+ if request.ServiceName == "" {+ c.JSON(http.StatusBadRequest, gin.H{"error": "serviceName is required"})+ return+ }++ typesFrom := request.FromDate+ if !request.ToDate.IsZero() {+ typesFrom = request.ToDate.AddDate(0, 0, -30)+ if request.FromDate.Before(typesFrom) {+ typesFrom = request.FromDate+ }+ }++ types, err := repositories.ProfileRepository.DiscoverTypes(c, projectId, request.ServiceName, typesFrom, request.ToDate)+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error discovering profile types: %w", err))+ return+ }+ if types == nil {+ types = []models.ProfileTypeInfo{}+ }+ c.JSON(http.StatusOK, types)+}+func (p profileController) GetFlameGraph(c *gin.Context) {projectId, err := middleware.GetProjectId(c)if err != nil {@@ -131,21 +235,14 @@ func (p profileController) GetFlameGraph(c *gin.Context) {return}- if len(request.Labels) > 0 {- var additional []string- if proj := cache.ProjectCache.GetById(projectId); proj != nil {- additional = proj.ProfileLabelAllowlist- }- allowed := profiling.LabelAllowKeys(additional)- for key := range request.Labels {- if utf8.RuneCountInString(key) > 100 || !slices.Contains(allowed, key) {- c.JSON(http.StatusBadRequest, gin.H{"error": "label filter key is not in the project's profile label allowlist"})- return- }- }+ if !validateProfileLabelFilters(c, projectId, request.Labels) {+ return+ }+ if !validateProfileCohort(c, request.AppVersion, request.ServerName) {+ return}- rows, err := repositories.ProfileRepository.GetFlameGraph(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.Labels)+ rows, err := repositories.ProfileRepository.GetFlameGraph(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.Labels, request.IsGauge, request.AppVersion, request.ServerName)if err != nil {c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error loading flame graph: %w", err))return@@ -154,6 +251,202 @@ func (p profileController) GetFlameGraph(c *gin.Context) {c.JSON(http.StatusOK, services.FoldFlameGraph(rows))}+func (p profileController) GetTopFunctions(c *gin.Context) {+ projectId, err := middleware.GetProjectId(c)+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ var request ProfileTopFunctionsRequest+ if err := c.ShouldBindJSON(&request); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }+ if request.ServiceName == "" || request.Type == "" {+ c.JSON(http.StatusBadRequest, gin.H{"error": "serviceName and type are required"})+ return+ }+ if !validateProfileLabelFilters(c, projectId, request.Labels) {+ return+ }+ if !validateProfileCohort(c, request.AppVersion, request.ServerName) {+ return+ }++ limit := request.Limit+ if limit <= 0 {+ limit = 25+ }+ if limit > 200 {+ limit = 200+ }++ rows, err := repositories.ProfileRepository.GetFlameGraph(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.Labels, request.IsGauge, request.AppVersion, request.ServerName)+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error loading top functions: %w", err))+ return+ }++ c.JSON(http.StatusOK, services.TopFunctions(rows, limit))+}++func (p profileController) DownloadPprof(c *gin.Context) {+ projectId, err := middleware.GetProjectId(c)+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ var request ProfileFlameGraphRequest+ if err := c.ShouldBindJSON(&request); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }+ if request.ServiceName == "" || request.Type == "" {+ c.JSON(http.StatusBadRequest, gin.H{"error": "serviceName and type are required"})+ return+ }+ if !validateProfileLabelFilters(c, projectId, request.Labels) {+ return+ }+ if !validateProfileCohort(c, request.AppVersion, request.ServerName) {+ return+ }++ rows, err := repositories.ProfileRepository.GetFlameGraph(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.Labels, request.IsGauge, request.AppVersion, request.ServerName)+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error loading profile for export: %w", err))+ return+ }+ if len(rows) == 0 {+ c.JSON(http.StatusNotFound, gin.H{"error": "no profile data for the selected range"})+ return+ }++ data, err := services.BuildPprof(request.Type, request.Unit, rows)+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error building pprof export: %w", err))+ return+ }++ c.Header("Content-Disposition", "attachment; filename=\""+pprofFilename(request.ServiceName, request.Type)+"\"")+ c.Data(http.StatusOK, "application/octet-stream", data)+}++func pprofFilename(serviceName, profileType string) string {+ safe := func(s string) string {+ out := make([]rune, 0, len(s))+ for _, r := range s {+ switch {+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_':+ out = append(out, r)+ default:+ out = append(out, '_')+ }+ }+ return string(out)+ }+ return safe(serviceName) + "-" + safe(profileType) + ".pprof"+}++func validateProfileLabelFilters(c *gin.Context, projectId uuid.UUID, labels map[string]string) bool {+ if len(labels) == 0 {+ return true+ }+ var additional []string+ if proj := cache.ProjectCache.GetById(projectId); proj != nil {+ additional = proj.ProfileLabelAllowlist+ }+ allowed := profiling.LabelAllowKeys(additional)+ for key := range labels {+ if utf8.RuneCountInString(key) > 100 || !slices.Contains(allowed, key) {+ c.JSON(http.StatusBadRequest, gin.H{"error": "label filter key is not in the project's profile label allowlist"})+ return false+ }+ }+ return true+}++func validateProfileCohort(c *gin.Context, appVersion, serverName string) bool {+ if utf8.RuneCountInString(appVersion) > 200 || utf8.RuneCountInString(serverName) > 200 {+ c.JSON(http.StatusBadRequest, gin.H{"error": "appVersion and serverName must be at most 200 characters"})+ return false+ }+ return true+}++func (p profileController) GetSeriesBreakdown(c *gin.Context) {+ projectId, err := middleware.GetProjectId(c)+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ var request ProfileSeriesBreakdownRequest+ if err := c.ShouldBindJSON(&request); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }+ if request.ServiceName == "" || request.Type == "" || request.Dimension == "" {+ c.JSON(http.StatusBadRequest, gin.H{"error": "serviceName, type and dimension are required"})+ return+ }+ if !validateProfileLabelFilters(c, projectId, request.Labels) {+ return+ }+ if !validateProfileCohort(c, request.AppVersion, request.ServerName) {+ return+ }++ groups, err := repositories.ProfileRepository.GetSeriesBreakdown(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate, request.IntervalMinutes, request.IsGauge, request.Labels, request.AppVersion, request.ServerName, request.Normalize, request.Dimension, request.Limit)+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error loading profile series breakdown: %w", err))+ return+ }++ out := make([]ProfileSeriesGroupResponse, 0, len(groups))+ for _, g := range groups {+ points := make([]ProfileSeriesPoint, 0, len(g.Points))+ for _, pt := range g.Points {+ points = append(points, ProfileSeriesPoint{Timestamp: pt.Timestamp, Value: pt.Value})+ }+ out = append(out, ProfileSeriesGroupResponse{Key: g.Key, Points: points})+ }+ c.JSON(http.StatusOK, out)+}++func (p profileController) DiscoverDimensions(c *gin.Context) {+ projectId, err := middleware.GetProjectId(c)+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))+ return+ }++ var request ProfileDimensionsRequest+ if err := c.ShouldBindJSON(&request); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }+ if request.ServiceName == "" || request.Type == "" {+ c.JSON(http.StatusBadRequest, gin.H{"error": "serviceName and type are required"})+ return+ }++ appVersions, serverNames, err := repositories.ProfileRepository.DiscoverDimensions(c, projectId, request.ServiceName, request.Type, request.FromDate, request.ToDate)+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error discovering profile dimensions: %w", err))+ return+ }+ if appVersions == nil {+ appVersions = []string{}+ }+ if serverNames == nil {+ serverNames = []string{}+ }+ c.JSON(http.StatusOK, gin.H{"appVersions": appVersions, "serverNames": serverNames})+}+func (p profileController) DiscoverLabels(c *gin.Context) {projectId, err := middleware.GetProjectId(c)if err != nil {diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.goindex 642d5a8b..0da38e6b 100644--- a/backend/app/controllers/routes.go+++ b/backend/app/controllers/routes.go@@ -98,7 +98,12 @@ func RegisterControllers(router *gin.RouterGroup) {router.POST("/profiles/grouped", middleware.UseAppAuth, middleware.RequireProjectAccess, ProfileController.FindGroupedByService)router.POST("/profiles/series", middleware.UseAppAuth, middleware.RequireProjectAccess, ProfileController.GetSeries)+ router.POST("/profiles/series/breakdown", middleware.UseAppAuth, middleware.RequireProjectAccess, ProfileController.GetSeriesBreakdown)+ router.POST("/profiles/dimensions", middleware.UseAppAuth, middleware.RequireProjectAccess, ProfileController.DiscoverDimensions)+ router.POST("/profiles/types", middleware.UseAppAuth, middleware.RequireProjectAccess, ProfileController.DiscoverTypes)router.POST("/profiles/flamegraph", middleware.UseAppAuth, middleware.RequireProjectAccess, ProfileController.GetFlameGraph)+ router.POST("/profiles/top", middleware.UseAppAuth, middleware.RequireProjectAccess, ProfileController.GetTopFunctions)+ router.POST("/profiles/pprof", middleware.UseAppAuth, middleware.RequireProjectAccess, ProfileController.DownloadPprof)router.POST("/profiles/labels", middleware.UseAppAuth, middleware.RequireProjectAccess, ProfileController.DiscoverLabels)router.POST("/ai-traces/grouped", middleware.UseAppAuth, middleware.RequireProjectAccess, AiTraceController.FindGroupedByTraceName)diff --git a/backend/app/migrations/ch/0071_add_unit_to_profiling_samples.up.sql b/backend/app/migrations/ch/0071_add_unit_to_profiling_samples.up.sqlnew file mode 100644index 00000000..1db9905d--- /dev/null+++ b/backend/app/migrations/ch/0071_add_unit_to_profiling_samples.up.sql@@ -0,0 +1 @@+ALTER TABLE profiling_samples ADD COLUMN IF NOT EXISTS unit LowCardinality(String) DEFAULT ''diff --git a/backend/app/migrations/ch/0072_add_is_gauge_to_profiling_samples.up.sql b/backend/app/migrations/ch/0072_add_is_gauge_to_profiling_samples.up.sqlnew file mode 100644index 00000000..4876af83--- /dev/null+++ b/backend/app/migrations/ch/0072_add_is_gauge_to_profiling_samples.up.sql@@ -0,0 +1 @@+ALTER TABLE profiling_samples ADD COLUMN IF NOT EXISTS is_gauge UInt8 DEFAULT 0diff --git a/backend/app/migrations/ch/0073_add_unit_to_profiles.up.sql b/backend/app/migrations/ch/0073_add_unit_to_profiles.up.sqlnew file mode 100644index 00000000..f2af962e--- /dev/null+++ b/backend/app/migrations/ch/0073_add_unit_to_profiles.up.sql@@ -0,0 +1 @@+ALTER TABLE profiles ADD COLUMN IF NOT EXISTS unit LowCardinality(String) DEFAULT ''diff --git a/backend/app/migrations/ch/0074_add_is_gauge_to_profiles.up.sql b/backend/app/migrations/ch/0074_add_is_gauge_to_profiles.up.sqlnew file mode 100644index 00000000..33a736f6--- /dev/null+++ b/backend/app/migrations/ch/0074_add_is_gauge_to_profiles.up.sql@@ -0,0 +1 @@+ALTER TABLE profiles ADD COLUMN IF NOT EXISTS is_gauge UInt8 DEFAULT 0diff --git a/backend/app/migrations/sqlite_telemetry/0013_add_unit_to_profiling_samples.up.sql b/backend/app/migrations/sqlite_telemetry/0013_add_unit_to_profiling_samples.up.sqlnew file mode 100644index 00000000..d1f8d56d--- /dev/null+++ b/backend/app/migrations/sqlite_telemetry/0013_add_unit_to_profiling_samples.up.sql@@ -0,0 +1 @@+ALTER TABLE profiling_samples ADD COLUMN unit TEXT NOT NULL DEFAULT ''diff --git a/backend/app/migrations/sqlite_telemetry/0014_add_is_gauge_to_profiling_samples.up.sql b/backend/app/migrations/sqlite_telemetry/0014_add_is_gauge_to_profiling_samples.up.sqlnew file mode 100644index 00000000..f3bc41b8--- /dev/null+++ b/backend/app/migrations/sqlite_telemetry/0014_add_is_gauge_to_profiling_samples.up.sql@@ -0,0 +1 @@+ALTER TABLE profiling_samples ADD COLUMN is_gauge INTEGER NOT NULL DEFAULT 0diff --git a/backend/app/migrations/sqlite_telemetry/0015_add_unit_to_profiles.up.sql b/backend/app/migrations/sqlite_telemetry/0015_add_unit_to_profiles.up.sqlnew file mode 100644index 00000000..38dc0a1c--- /dev/null+++ b/backend/app/migrations/sqlite_telemetry/0015_add_unit_to_profiles.up.sql@@ -0,0 +1 @@+ALTER TABLE profiles ADD COLUMN unit TEXT NOT NULL DEFAULT ''diff --git a/backend/app/migrations/sqlite_telemetry/0016_add_is_gauge_to_profiles.up.sql b/backend/app/migrations/sqlite_telemetry/0016_add_is_gauge_to_profiles.up.sqlnew file mode 100644index 00000000..6fe078bb--- /dev/null+++ b/backend/app/migrations/sqlite_telemetry/0016_add_is_gauge_to_profiles.up.sql@@ -0,0 +1 @@+ALTER TABLE profiles ADD COLUMN is_gauge INTEGER NOT NULL DEFAULT 0diff --git a/backend/app/models/profile.model.go b/backend/app/models/profile.model.goindex a7152641..3ee131b6 100644--- a/backend/app/models/profile.model.go+++ b/backend/app/models/profile.model.go@@ -19,6 +19,8 @@ type ProfileSample struct {ProfileId uuid.UUID `json:"profileId" ch:"profile_id"`ServiceName string `json:"serviceName" ch:"service_name"`Type string `json:"type" ch:"type"`+ Unit string `json:"unit" ch:"unit"`+ IsGauge bool `json:"isGauge" ch:"is_gauge"`Start time.Time `json:"start" ch:"start_time"`End time.Time `json:"end" ch:"end_time"`StackHash uint64 `json:"stackHash" ch:"stack_hash"`@@ -33,10 +35,19 @@ type ProfileSample struct {type ProfileGroup struct {ServiceName string `json:"serviceName" ch:"service_name"`Type string `json:"type" ch:"profile_type"`+ Unit string `json:"unit" ch:"unit"`+ IsGauge bool `json:"isGauge" ch:"is_gauge"`ProfileCount int64 `json:"profileCount" ch:"profile_count"`SampleCount int64 `json:"sampleCount" ch:"sample_count"`TotalValue int64 `json:"totalValue" ch:"total_value"`LastSeen time.Time `json:"lastSeen" ch:"last_seen"`+ Sparkline []float64 `json:"sparkline"`+}++type ProfileTypeInfo struct {+ Type string `json:"type" ch:"type"`+ Unit string `json:"unit" ch:"unit"`+ IsGauge bool `json:"isGauge" ch:"is_gauge"`}type ProfileStackValue struct {@@ -44,6 +55,11 @@ type ProfileStackValue struct {Value int64 `json:"value"`}+type ProfileSeriesGroup struct {+ Key string `json:"key"`+ Points []TimeSeriesPoint `json:"points"`+}+type Profile struct {Id uuid.UUID `json:"id" ch:"id"`ProjectId uuid.UUID `json:"projectId" ch:"project_id"`@@ -51,6 +67,8 @@ type Profile struct {Duration time.Duration `json:"duration" ch:"duration"`ServiceName string `json:"serviceName" ch:"service_name"`ProfileType string `json:"profileType" ch:"profile_type"`+ Unit string `json:"unit" ch:"unit"`+ IsGauge bool `json:"isGauge" ch:"is_gauge"`SampleCount uint64 `json:"sampleCount" ch:"sample_count"`TotalValue int64 `json:"totalValue" ch:"total_value"`ServerName string `json:"serverName" ch:"server_name"`diff --git a/backend/app/profiling/archive_test.go b/backend/app/profiling/archive_test.goindex f00dcb9c..19dda10b 100644--- a/backend/app/profiling/archive_test.go+++ b/backend/app/profiling/archive_test.go@@ -74,8 +74,8 @@ func TestStampArchive(t *testing.T) {t.Run("enabled stamps all rows with one key", func(t *testing.T) {config.Config.ProfileArchiveRaw = "true"profiles := []models.Profile{- {ProfileType: TypeHeapAllocSpace},- {ProfileType: TypeHeapInuseSpace},+ {ProfileType: "alloc_space"},+ {ProfileType: "inuse_space"},}key, ok := StampArchive(projectId, recordedAt, profiles)@@ -98,7 +98,7 @@ func TestStampArchive(t *testing.T) {t.Run("disabled is a no-op", func(t *testing.T) {config.Config.ProfileArchiveRaw = "false"- profiles := []models.Profile{{ProfileType: TypeCPUNanos}}+ profiles := []models.Profile{{ProfileType: "cpu"}}key, ok := StampArchive(projectId, recordedAt, profiles)if ok || key != "" {diff --git a/backend/app/profiling/gauge_test.go b/backend/app/profiling/gauge_test.gonew file mode 100644index 00000000..83d4d204--- /dev/null+++ b/backend/app/profiling/gauge_test.go@@ -0,0 +1,18 @@+package profiling++import "testing"++func TestGaugeFromName(t *testing.T) {+ gauges := []string{"inuse_space", "inuse_objects", "goroutine", "goroutines", "threads", "heap_live", "in_use"}+ for _, n := range gauges {+ if !gaugeFromName(n) {+ t.Errorf("gaugeFromName(%q) = false, want true", n)+ }+ }+ counters := []string{"cpu", "alloc_space", "alloc_objects", "mutex", "block", "lock", "wall", "samples"}+ for _, n := range counters {+ if gaugeFromName(n) {+ t.Errorf("gaugeFromName(%q) = true, want false", n)+ }+ }+}diff --git a/backend/app/profiling/model.go b/backend/app/profiling/model.goindex b53ca6b6..47b367f3 100644--- a/backend/app/profiling/model.go+++ b/backend/app/profiling/model.go@@ -7,16 +7,12 @@ import ("time")-const (- TypeCPUNanos = "go:profile_cpu:nanoseconds"- TypeHeapInuseSpace = "go:profile_heap:inuse_space"- TypeHeapAllocSpace = "go:profile_heap:alloc_space"-)--var keptSampleTypes = map[string]string{- "cpu": TypeCPUNanos,- "inuse_space": TypeHeapInuseSpace,- "alloc_space": TypeHeapAllocSpace,+func gaugeFromName(name string) bool {+ n := strings.ToLower(name)+ if n == "goroutine" || n == "goroutines" || n == "threads" {+ return true+ }+ return strings.Contains(n, "inuse") || strings.Contains(n, "in_use") || strings.Contains(n, "live")}const LabelEndpoint = "endpoint"@@ -44,10 +40,6 @@ func LabelAllowKeys(additional []string) []string {return keys}-func IsGauge(profileType string) bool {- return profileType == TypeHeapInuseSpace-}-type Stack struct {Hash uint64Frames []string@@ -55,6 +47,8 @@ type Stack struct {type Sample struct {Type string+ Unit string+ IsGauge boolStackHash uint64Value int64Labels map[string]stringdiff --git a/backend/app/profiling/otlp_decoder.go b/backend/app/profiling/otlp_decoder.goindex bf361a7d..71a75b40 100644--- a/backend/app/profiling/otlp_decoder.go+++ b/backend/app/profiling/otlp_decoder.go@@ -45,10 +45,12 @@ func decodeProfile(ctx IngestContext, serviceName string, resolver *stackResolveif p.SampleType == nil {return Decoded{}, false}- internalType, ok := keptSampleTypes[resolver.stringAt(p.SampleType.TypeStrindex)]- if !ok {+ internalType := resolver.stringAt(p.SampleType.TypeStrindex)+ if internalType == "" {return Decoded{}, false}+ unit := resolver.stringAt(p.SampleType.UnitStrindex)+ isGauge := gaugeFromName(internalType)start := ctx.ReceivedAtif p.TimeUnixNano > 0 {@@ -101,7 +103,7 @@ func decodeProfile(ctx IngestContext, serviceName string, resolver *stackResolvedecoded.Stacks = append(decoded.Stacks, Stack{Hash: hash, Frames: frames})}for key, agg := range values {- decoded.Samples = append(decoded.Samples, Sample{Type: key.typ, StackHash: key.stackHash, Value: agg.value, Labels: agg.labels})+ decoded.Samples = append(decoded.Samples, Sample{Type: key.typ, Unit: unit, IsGauge: isGauge, StackHash: key.stackHash, Value: agg.value, Labels: agg.labels})}return decoded, true}diff --git a/backend/app/profiling/otlp_decoder_test.go b/backend/app/profiling/otlp_decoder_test.goindex 6f6a4540..90c36710 100644--- a/backend/app/profiling/otlp_decoder_test.go+++ b/backend/app/profiling/otlp_decoder_test.go@@ -188,11 +188,11 @@ func TestOTLPDecoder_CPU_ExplodesDistinctStacks(t *testing.T) {wantWork := HashFrames([]string{"main.main", "main.work"})wantIdle := HashFrames([]string{"main.main", "main.idle"})- if samples[sampleKey{TypeCPUNanos, wantWork}] != 300 {- t.Errorf("main->work cpu = %d, want 300", samples[sampleKey{TypeCPUNanos, wantWork}])+ if samples[sampleKey{"cpu", wantWork}] != 300 {+ t.Errorf("main->work cpu = %d, want 300", samples[sampleKey{"cpu", wantWork}])}- if samples[sampleKey{TypeCPUNanos, wantIdle}] != 100 {- t.Errorf("main->idle cpu = %d, want 100", samples[sampleKey{TypeCPUNanos, wantIdle}])+ if samples[sampleKey{"cpu", wantIdle}] != 100 {+ t.Errorf("main->idle cpu = %d, want 100", samples[sampleKey{"cpu", wantIdle}])}if got := stacks[wantWork]; len(got) != 2 || got[0] != "main.main" || got[1] != "main.work" {t.Errorf("frames = %v, want [main.main main.work] (root-first)", got)@@ -217,45 +217,111 @@ func TestOTLPDecoder_DedupesIdenticalStacks(t *testing.T) {t.Fatalf("expected 1 deduped sample, got %d", len(samples))}want := HashFrames([]string{"main.main", "main.work"})- if samples[sampleKey{TypeCPUNanos, want}] != 250 {- t.Errorf("summed value = %d, want 250", samples[sampleKey{TypeCPUNanos, want}])+ if samples[sampleKey{"cpu", want}] != 250 {+ t.Errorf("summed value = %d, want 250", samples[sampleKey{"cpu", want}])}}-func TestOTLPDecoder_Heap_KeepsSpaceTypesOnly(t *testing.T) {+func TestOTLPDecoder_Heap_KeepsObjectAndSpaceTypes(t *testing.T) {b := newOTLPBuilder()b.serviceName = "checkout"s := b.frameStack("main.main", "main.allocate")b.profile("inuse_space", "bytes", 1_700_000_000_000_000_000, 0, otlpSample(s, 2048))b.profile("alloc_space", "bytes", 1_700_000_000_000_000_000, 0, otlpSample(s, 4096))b.profile("inuse_objects", "count", 1_700_000_000_000_000_000, 0, otlpSample(s, 2))+ b.profile("alloc_objects", "count", 1_700_000_000_000_000_000, 0, otlpSample(s, 5))out := decodeOTLPAll(t, b.build(t))samples := flattenSamples(out)want := HashFrames([]string{"main.main", "main.allocate"})- if samples[sampleKey{TypeHeapInuseSpace, want}] != 2048 {- t.Errorf("inuse_space = %d, want 2048", samples[sampleKey{TypeHeapInuseSpace, want}])+ expected := map[string]int64{+ "inuse_space": 2048,+ "alloc_space": 4096,+ "inuse_objects": 2,+ "alloc_objects": 5,+ }+ for typ, wantValue := range expected {+ if samples[sampleKey{typ, want}] != wantValue {+ t.Errorf("%s = %d, want %d", typ, samples[sampleKey{typ, want}], wantValue)+ }}- if samples[sampleKey{TypeHeapAllocSpace, want}] != 4096 {- t.Errorf("alloc_space = %d, want 4096", samples[sampleKey{TypeHeapAllocSpace, want}])+ if len(samples) != len(expected) {+ t.Errorf("emitted %d sample types, want %d", len(samples), len(expected))}- for k := range samples {- if k.typ != TypeHeapInuseSpace && k.typ != TypeHeapAllocSpace {- t.Errorf("unexpected sample type emitted: %q", k.typ)- }+}++func TestOTLPDecoder_GoroutineMutexBlock(t *testing.T) {+ cases := []struct {+ sampleTyp string+ unit string+ internal string+ }{+ {"goroutine", "count", "goroutine"},+ {"mutex", "nanoseconds", "mutex"},+ {"block", "nanoseconds", "block"},+ }+ for _, tc := range cases {+ t.Run(tc.sampleTyp, func(t *testing.T) {+ b := newOTLPBuilder()+ b.serviceName = "checkout"+ s := b.frameStack("main.main", "sync.(*Mutex).Lock")+ b.profile(tc.sampleTyp, tc.unit, 1_700_000_000_000_000_000, 0, otlpSample(s, 42))++ out := decodeOTLPAll(t, b.build(t))+ samples := flattenSamples(out)+ want := HashFrames([]string{"main.main", "sync.(*Mutex).Lock"})+ if samples[sampleKey{tc.internal, want}] != 42 {+ t.Errorf("%s = %d, want 42", tc.internal, samples[sampleKey{tc.internal, want}])+ }+ })}}-func TestOTLPDecoder_UnsupportedTypeYieldsNoSamples(t *testing.T) {+func TestOTLPDecoder_KeepsArbitraryCrossLanguageType(t *testing.T) {b := newOTLPBuilder()b.serviceName = "checkout"- s := b.frameStack("main.main")+ s := b.frameStack("main.main", "sync.(*Mutex).Lock")+ b.profile("lock", "nanoseconds", 1_700_000_000_000_000_000, 0, otlpSample(s, 42))++ out := decodeOTLPAll(t, b.build(t))+ var got []Sample+ for _, d := range out {+ got = append(got, d.Samples...)+ }+ if len(got) != 1 {+ t.Fatalf("expected 1 sample for arbitrary type, got %d", len(got))+ }+ if got[0].Type != "lock" || got[0].Unit != "nanoseconds" || got[0].Value != 42 {+ t.Errorf("sample = %+v, want type=lock unit=nanoseconds value=42", got[0])+ }+ if got[0].IsGauge {+ t.Errorf("lock should not be a gauge by name heuristic")+ }+}++func TestOTLPDecoder_GaugeFromNameForInuse(t *testing.T) {+ b := newOTLPBuilder()+ b.serviceName = "checkout"+ s := b.frameStack("main.main", "main.alloc")+ b.profile("inuse_space", "bytes", 1_700_000_000_000_000_000, 0, otlpSample(s, 2048))b.profile("goroutine", "count", 1_700_000_000_000_000_000, 0, otlpSample(s, 7))out := decodeOTLPAll(t, b.build(t))- if got := len(flattenSamples(out)); got != 0 {- t.Errorf("expected 0 samples for unsupported type, got %d", got)+ byType := map[string]Sample{}+ for _, d := range out {+ for _, smp := range d.Samples {+ byType[smp.Type] = smp+ }+ }+ if !byType["inuse_space"].IsGauge {+ t.Errorf("inuse_space should be a gauge (name heuristic)")+ }+ if !byType["goroutine"].IsGauge {+ t.Errorf("goroutine should be a gauge (name heuristic)")+ }+ if byType["inuse_space"].Unit != "bytes" {+ t.Errorf("inuse_space unit = %q, want bytes", byType["inuse_space"].Unit)}}@@ -269,8 +335,8 @@ func TestOTLPDecoder_TimestampsOnlySampleCountsTimestamps(t *testing.T) {out := decodeOTLPAll(t, b.build(t))samples := flattenSamples(out)want := HashFrames([]string{"main.main", "main.work"})- if samples[sampleKey{TypeCPUNanos, want}] != 3 {- t.Errorf("value = %d, want 3 (one per timestamp when Values is empty)", samples[sampleKey{TypeCPUNanos, want}])+ if samples[sampleKey{"cpu", want}] != 3 {+ t.Errorf("value = %d, want 3 (one per timestamp when Values is empty)", samples[sampleKey{"cpu", want}])}}@@ -398,10 +464,10 @@ func TestDecoderParity_PprofVsOTLP(t *testing.T) {t.Errorf("stack rows differ:\npprof=%v\notlp=%v", pprofStacks, otlpStacks)}- pprofSmpl := flattenSamples([]Decoded{fromPprof})- otlpSmpl := flattenSamples(fromOTLP)+ pprofSmpl := cpuOnly(flattenSamples([]Decoded{fromPprof}))+ otlpSmpl := cpuOnly(flattenSamples(fromOTLP))if len(pprofSmpl) != len(otlpSmpl) {- t.Fatalf("sample count differs: pprof=%d otlp=%d", len(pprofSmpl), len(otlpSmpl))+ t.Fatalf("cpu sample count differs: pprof=%d otlp=%d", len(pprofSmpl), len(otlpSmpl))}for k, v := range pprofSmpl {if otlpSmpl[k] != v {@@ -410,6 +476,16 @@ func TestDecoderParity_PprofVsOTLP(t *testing.T) {}}+func cpuOnly(m map[sampleKey]int64) map[sampleKey]int64 {+ out := map[sampleKey]int64{}+ for k, v := range m {+ if k.typ == "cpu" {+ out[k] = v+ }+ }+ return out+}+func TestOTLPDecoder_ExtractsAllowlistedLabels(t *testing.T) {b := newOTLPBuilder()b.serviceName = "checkout"diff --git a/backend/app/profiling/pprof_decoder.go b/backend/app/profiling/pprof_decoder.goindex 1a3afc3c..e63a880f 100644--- a/backend/app/profiling/pprof_decoder.go+++ b/backend/app/profiling/pprof_decoder.go@@ -33,14 +33,20 @@ func (PprofDecoder) Decode(ctx IngestContext, payload []byte) ([]Decoded, error)}type keptType struct {- index int- typ string+ index int+ typ string+ unit string+ isGauge bool}var kept []keptType+ typeMeta := map[string]keptType{}for i, st := range p.SampleType {- if internal, ok := keptSampleTypes[st.Type]; ok {- kept = append(kept, keptType{index: i, typ: internal})+ if st.Type == "" {+ continue}+ k := keptType{index: i, typ: st.Type, unit: st.Unit, isGauge: gaugeFromName(st.Type)}+ kept = append(kept, k)+ typeMeta[st.Type] = k}meta := Meta{@@ -85,8 +91,11 @@ func (PprofDecoder) Decode(ctx IngestContext, payload []byte) ([]Decoded, error)decoded.Stacks = append(decoded.Stacks, Stack{Hash: hash, Frames: frames})}for key, agg := range values {+ m := typeMeta[key.typ]decoded.Samples = append(decoded.Samples, Sample{Type: key.typ,+ Unit: m.unit,+ IsGauge: m.isGauge,StackHash: key.stackHash,Value: agg.value,Labels: agg.labels,diff --git a/backend/app/profiling/pprof_decoder_test.go b/backend/app/profiling/pprof_decoder_test.goindex 1fb84f32..0e6d55e8 100644--- a/backend/app/profiling/pprof_decoder_test.go+++ b/backend/app/profiling/pprof_decoder_test.go@@ -104,7 +104,7 @@ func TestPprofDecoder_CPU_ExplodesDistinctStacks(t *testing.T) {d := decodeOne(t, payload)- cpu := sampleByType(d, TypeCPUNanos)+ cpu := sampleByType(d, "cpu")if len(cpu) != 2 {t.Fatalf("expected 2 cpu samples, got %d", len(cpu))}@@ -149,7 +149,7 @@ func TestPprofDecoder_DedupesIdenticalStacks(t *testing.T) {d := decodeOne(t, payload)- cpu := sampleByType(d, TypeCPUNanos)+ cpu := sampleByType(d, "cpu")if len(cpu) != 1 {t.Fatalf("expected 1 deduped cpu sample, got %d", len(cpu))}@@ -161,7 +161,7 @@ func TestPprofDecoder_DedupesIdenticalStacks(t *testing.T) {}}-func TestPprofDecoder_Heap_KeepsSpaceTypesOnly(t *testing.T) {+func TestPprofDecoder_Heap_KeepsObjectAndSpaceTypes(t *testing.T) {main := fn(1, "main.main", "main.go")alloc := fn(2, "main.allocate", "alloc.go")lMain := loc(1, profile.Line{Function: main, Line: 10})@@ -185,19 +185,57 @@ func TestPprofDecoder_Heap_KeepsSpaceTypesOnly(t *testing.T) {}d := decodeOne(t, writeProfile(t, p))- inuse := sampleByType(d, TypeHeapInuseSpace)- allocS := sampleByType(d, TypeHeapAllocSpace)- if len(inuse) != 1 || inuse[0].Value != 2048 {- t.Errorf("inuse_space = %+v, want one sample value 2048", inuse)+ want := map[string]int64{+ "alloc_objects": 5,+ "alloc_space": 4096,+ "inuse_objects": 2,+ "inuse_space": 2048,}- if len(allocS) != 1 || allocS[0].Value != 4096 {- t.Errorf("alloc_space = %+v, want one sample value 4096", allocS)- }- for _, s := range d.Samples {- if s.Type != TypeHeapInuseSpace && s.Type != TypeHeapAllocSpace {- t.Errorf("unexpected sample type emitted: %q", s.Type)+ for typ, wantValue := range want {+ got := sampleByType(d, typ)+ if len(got) != 1 || got[0].Value != wantValue {+ t.Errorf("%s = %+v, want one sample value %d", typ, got, wantValue)}}+ if len(d.Samples) != len(want) {+ t.Errorf("emitted %d samples, want %d (all four heap types)", len(d.Samples), len(want))+ }+}++func TestPprofDecoder_GoroutineMutexBlock(t *testing.T) {+ main := fn(1, "main.main", "main.go")+ wait := fn(2, "sync.(*Mutex).Lock", "mutex.go")+ lMain := loc(1, profile.Line{Function: main, Line: 10})+ lWait := loc(2, profile.Line{Function: wait, Line: 20})++ cases := []struct {+ name string+ sampleTyp string+ unit string+ internal string+ }{+ {"goroutine", "goroutine", "count", "goroutine"},+ {"mutex", "mutex", "nanoseconds", "mutex"},+ {"block", "block", "nanoseconds", "block"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ p := &profile.Profile{+ SampleType: []*profile.ValueType{{Type: tc.sampleTyp, Unit: tc.unit}},+ PeriodType: &profile.ValueType{Type: tc.sampleTyp, Unit: tc.unit},+ Period: 1,+ TimeNanos: 1_700_000_000_000_000_000,+ Sample: []*profile.Sample{{Location: []*profile.Location{lWait, lMain}, Value: []int64{42}}},+ Function: []*profile.Function{main, wait},+ Location: []*profile.Location{lMain, lWait},+ }+ d := decodeOne(t, writeProfile(t, p))+ got := sampleByType(d, tc.internal)+ if len(got) != 1 || got[0].Value != 42 {+ t.Errorf("%s = %+v, want one sample value 42", tc.internal, got)+ }+ })+ }}func TestPprofDecoder_InlinedFramesExpand(t *testing.T) {@@ -283,7 +321,7 @@ func TestPprofDecoder_DropsZeroValueSamples(t *testing.T) {}d := decodeOne(t, writeProfile(t, p))- inuse := sampleByType(d, TypeHeapInuseSpace)+ inuse := sampleByType(d, "inuse_space")if len(inuse) != 1 {t.Fatalf("expected 1 inuse_space sample (zero dropped), got %d", len(inuse))}@@ -291,32 +329,60 @@ func TestPprofDecoder_DropsZeroValueSamples(t *testing.T) {if inuse[0].StackHash != wantLive || inuse[0].Value != 4096 {t.Errorf("inuse sample = %+v, want live stack value 4096", inuse[0])}- if got := len(sampleByType(d, TypeHeapAllocSpace)); got != 2 {+ if got := len(sampleByType(d, "alloc_space")); got != 2 {t.Errorf("alloc_space samples = %d, want 2", got)}}-func TestPprofDecoder_UnsupportedTypesYieldNoSamples(t *testing.T) {+func TestPprofDecoder_KeepsArbitraryTypeWithUnit(t *testing.T) {main := fn(1, "main.main", "main.go")lMain := loc(1, profile.Line{Function: main, Line: 10})p := &profile.Profile{- SampleType: []*profile.ValueType{{Type: "goroutine", Unit: "count"}},- PeriodType: &profile.ValueType{Type: "goroutine", Unit: "count"},+ SampleType: []*profile.ValueType{{Type: "threadcreate", Unit: "count"}},+ PeriodType: &profile.ValueType{Type: "threadcreate", Unit: "count"},Period: 1,TimeNanos: 1_700_000_000_000_000_000,Sample: []*profile.Sample{{Location: []*profile.Location{lMain}, Value: []int64{7}}},Function: []*profile.Function{main},Location: []*profile.Location{lMain},}- out, err := PprofDecoder{}.Decode(testIngest, writeProfile(t, p))- if err != nil {- t.Fatalf("unexpected error on unsupported profile: %v", err)+ d := decodeOne(t, writeProfile(t, p))+ got := sampleByType(d, "threadcreate")+ if len(got) != 1 || got[0].Value != 7 {+ t.Fatalf("threadcreate = %+v, want one sample value 7 (arbitrary types kept)", got)}- if len(out) != 1 {- t.Fatalf("expected 1 decoded profile, got %d", len(out))+ if got[0].Unit != "count" {+ t.Errorf("threadcreate unit = %q, want count", got[0].Unit)+ }+}++func TestPprofDecoder_GaugeAndUnitFromHeapTypes(t *testing.T) {+ main := fn(1, "main.main", "main.go")+ alloc := fn(2, "main.allocate", "alloc.go")+ lMain := loc(1, profile.Line{Function: main, Line: 10})+ lAlloc := loc(2, profile.Line{Function: alloc, Line: 20})+ p := &profile.Profile{+ SampleType: []*profile.ValueType{+ {Type: "alloc_space", Unit: "bytes"},+ {Type: "inuse_space", Unit: "bytes"},+ },+ PeriodType: &profile.ValueType{Type: "space", Unit: "bytes"},+ Period: 524288,+ TimeNanos: 1_700_000_000_000_000_000,+ Sample: []*profile.Sample{+ {Location: []*profile.Location{lAlloc, lMain}, Value: []int64{4096, 2048}},+ },+ Function: []*profile.Function{main, alloc},+ Location: []*profile.Location{lMain, lAlloc},+ }+ d := decodeOne(t, writeProfile(t, p))+ inuse := sampleByType(d, "inuse_space")+ alloc2 := sampleByType(d, "alloc_space")+ if len(inuse) != 1 || !inuse[0].IsGauge || inuse[0].Unit != "bytes" {+ t.Errorf("inuse_space = %+v, want gauge with unit bytes", inuse)}- if len(out[0].Samples) != 0 {- t.Errorf("expected 0 samples for unsupported types, got %d", len(out[0].Samples))+ if len(alloc2) != 1 || alloc2[0].IsGauge {+ t.Errorf("alloc_space = %+v, want counter (not gauge)", alloc2)}}diff --git a/backend/app/profiling/pprof_labels_test.go b/backend/app/profiling/pprof_labels_test.goindex a11931a5..6a887d5b 100644--- a/backend/app/profiling/pprof_labels_test.go+++ b/backend/app/profiling/pprof_labels_test.go@@ -26,7 +26,7 @@ func TestPprofDecoder_KeepsOnlyAllowlistedLabels(t *testing.T) {}d := decodeOne(t, labeledCPU(t, samples, []*profile.Function{main, work}, []*profile.Location{lMain, lWork}))- cpu := sampleByType(d, TypeCPUNanos)+ cpu := sampleByType(d, "cpu")if len(cpu) != 1 {t.Fatalf("expected 1 sample, got %d", len(cpu))}@@ -52,7 +52,7 @@ func TestPprofDecoder_HonorsAdditionalAllowlistedKeys(t *testing.T) {if err != nil {t.Fatalf("Decode: %v", err)}- cpu := sampleByType(out[0], TypeCPUNanos)+ cpu := sampleByType(out[0], "cpu")if len(cpu) != 1 {t.Fatalf("expected 1 sample, got %d", len(cpu))}@@ -81,7 +81,7 @@ func TestPprofDecoder_LabelsSeparateTheDedup(t *testing.T) {samples := []*profile.Sample{mk("/a", 100), mk("/b", 50), mk("/a", 25)}d := decodeOne(t, labeledCPU(t, samples, []*profile.Function{main, work}, []*profile.Location{lMain, lWork}))- cpu := sampleByType(d, TypeCPUNanos)+ cpu := sampleByType(d, "cpu")if len(cpu) != 2 {t.Fatalf("expected 2 samples (one per endpoint), got %d", len(cpu))}@@ -106,7 +106,7 @@ func TestPprofDecoder_NoLabelsStaysEmpty(t *testing.T) {samples := []*profile.Sample{{Location: []*profile.Location{lMain}, Value: []int64{1, 100}}}d := decodeOne(t, labeledCPU(t, samples, []*profile.Function{main}, []*profile.Location{lMain}))- cpu := sampleByType(d, TypeCPUNanos)+ cpu := sampleByType(d, "cpu")if len(cpu) != 1 {t.Fatalf("expected 1 sample, got %d", len(cpu))}@@ -119,7 +119,7 @@ func TestBuildRows_CarriesSampleLabels(t *testing.T) {decoded := []Decoded{{Meta: Meta{ServiceName: "svc"},Stacks: []Stack{{Hash: 1, Frames: []string{"main.main"}}},- Samples: []Sample{{Type: TypeCPUNanos, StackHash: 1, Value: 10, Labels: map[string]string{LabelEndpoint: "/x"}}},+ Samples: []Sample{{Type: "cpu", StackHash: 1, Value: 10, Labels: map[string]string{LabelEndpoint: "/x"}}},}}_, samples, _ := BuildRows(uuid.New(), decoded)if len(samples) != 1 {@@ -147,7 +147,7 @@ func TestPprofDecoder_DropsNumericLabels(t *testing.T) {if err != nil {t.Fatalf("Decode: %v", err)}- cpu := sampleByType(out[0], TypeCPUNanos)+ cpu := sampleByType(out[0], "cpu")if len(cpu) != 1 {t.Fatalf("expected 1 sample, got %d", len(cpu))}diff --git a/backend/app/profiling/rows.go b/backend/app/profiling/rows.goindex 7b93fcf6..afc2daa8 100644--- a/backend/app/profiling/rows.go+++ b/backend/app/profiling/rows.go@@ -46,6 +46,8 @@ func BuildRows(projectId uuid.UUID, decoded []Decoded) ([]models.ProfileStack, [Duration: d.Meta.End.Sub(d.Meta.Start),ServiceName: d.Meta.ServiceName,ProfileType: s.Type,+ Unit: s.Unit,+ IsGauge: s.IsGauge,ServerName: d.Meta.ServerName,AppVersion: d.Meta.AppVersion,Attributes: d.Meta.Attributes,@@ -62,6 +64,8 @@ func BuildRows(projectId uuid.UUID, decoded []Decoded) ([]models.ProfileStack, [ProfileId: p.Id,ServiceName: d.Meta.ServiceName,Type: s.Type,+ Unit: s.Unit,+ IsGauge: s.IsGauge,Start: d.Meta.Start,End: d.Meta.End,StackHash: s.StackHash,diff --git a/backend/app/profiling/rows_test.go b/backend/app/profiling/rows_test.goindex ab557ac4..9b50aa93 100644--- a/backend/app/profiling/rows_test.go+++ b/backend/app/profiling/rows_test.go@@ -33,8 +33,8 @@ func TestBuildRows_SingleType(t *testing.T) {{Hash: h2, Frames: []string{"main.main", "main.idle"}},},Samples: []Sample{- {Type: TypeCPUNanos, StackHash: h1, Value: 300},- {Type: TypeCPUNanos, StackHash: h2, Value: 100},+ {Type: "cpu", StackHash: h1, Value: 300},+ {Type: "cpu", StackHash: h2, Value: 100},},}@@ -56,7 +56,7 @@ func TestBuildRows_SingleType(t *testing.T) {t.Fatalf("profiles = %d, want 1", len(profiles))}p := profiles[0]- if p.ProfileType != TypeCPUNanos || p.SampleCount != 2 || p.TotalValue != 400 {+ if p.ProfileType != "cpu" || p.SampleCount != 2 || p.TotalValue != 400 {t.Errorf("profile = (%s, count=%d, total=%d), want (cpu, 2, 400)", p.ProfileType, p.SampleCount, p.TotalValue)}if p.ServiceName != "checkout" || p.ServerName != "pod-a" || p.AppVersion != "1.2.3" {@@ -76,7 +76,7 @@ func TestBuildRows_SingleType(t *testing.T) {if s.ProfileId != p.Id {t.Errorf("sample ProfileId = %v, want %v", s.ProfileId, p.Id)}- if s.Type != TypeCPUNanos || s.ProjectId != projectId || s.ServiceName != "checkout" {+ if s.Type != "cpu" || s.ProjectId != projectId || s.ServiceName != "checkout" {t.Errorf("sample fields wrong: %+v", s)}if !s.Start.Equal(start) || !s.End.Equal(d.Meta.End) {@@ -94,8 +94,8 @@ func TestBuildRows_MultiTypeSplitsProfiles(t *testing.T) {Meta: Meta{ServiceName: "checkout", Start: start, End: start},Stacks: []Stack{{Hash: h1, Frames: []string{"main.main", "main.work"}}},Samples: []Sample{- {Type: TypeCPUNanos, StackHash: h1, Value: 300},- {Type: TypeHeapInuseSpace, StackHash: h1, Value: 2048},+ {Type: "cpu", StackHash: h1, Value: 300},+ {Type: "inuse_space", StackHash: h1, Value: 2048},},}@@ -104,11 +104,11 @@ func TestBuildRows_MultiTypeSplitsProfiles(t *testing.T) {if len(profiles) != 2 {t.Fatalf("profiles = %d, want 2 (one per type)", len(profiles))}- cpu, ok := profileByType(profiles, TypeCPUNanos)+ cpu, ok := profileByType(profiles, "cpu")if !ok {t.Fatalf("no cpu profile row")}- heap, ok := profileByType(profiles, TypeHeapInuseSpace)+ heap, ok := profileByType(profiles, "inuse_space")if !ok {t.Fatalf("no heap profile row")}@@ -121,11 +121,11 @@ func TestBuildRows_MultiTypeSplitsProfiles(t *testing.T) {for _, s := range samples {switch s.Type {- case TypeCPUNanos:+ case "cpu":if s.ProfileId != cpu.Id {t.Errorf("cpu sample linked to %v, want %v", s.ProfileId, cpu.Id)}- case TypeHeapInuseSpace:+ case "inuse_space":if s.ProfileId != heap.Id {t.Errorf("heap sample linked to %v, want %v", s.ProfileId, heap.Id)}@@ -150,8 +150,8 @@ func TestBuildRows_PerTypeProfileRowsCarryProvenance(t *testing.T) {{Hash: 0xAA, Frames: []string{"main.main", "main.work"}},},Samples: []Sample{- {Type: TypeHeapAllocSpace, StackHash: 0xAA, Value: 4096},- {Type: TypeHeapInuseSpace, StackHash: 0xAA, Value: 2048},+ {Type: "alloc_space", StackHash: 0xAA, Value: 4096},+ {Type: "inuse_space", StackHash: 0xAA, Value: 2048},},}@@ -177,10 +177,10 @@ func TestBuildRows_PerTypeProfileRowsCarryProvenance(t *testing.T) {t.Errorf("profile %q SampleCount = %d, want 1", p.ProfileType, p.SampleCount)}}- if byType[TypeHeapAllocSpace].TotalValue != 4096 || byType[TypeHeapInuseSpace].TotalValue != 2048 {- t.Errorf("totals wrong: alloc=%d inuse=%d", byType[TypeHeapAllocSpace].TotalValue, byType[TypeHeapInuseSpace].TotalValue)+ if byType["alloc_space"].TotalValue != 4096 || byType["inuse_space"].TotalValue != 2048 {+ t.Errorf("totals wrong: alloc=%d inuse=%d", byType["alloc_space"].TotalValue, byType["inuse_space"].TotalValue)}- if byType[TypeHeapAllocSpace].Id == byType[TypeHeapInuseSpace].Id {+ if byType["alloc_space"].Id == byType["inuse_space"].Id {t.Error("per-type profiles must have distinct ids")}@@ -200,12 +200,12 @@ func TestBuildRows_MergesAcrossDecodedBatch(t *testing.T) {d1 := Decoded{Meta: Meta{ServiceName: "api", Start: start, End: start.Add(10 * time.Second)},Stacks: []Stack{{Hash: 1, Frames: []string{"main.main"}}},- Samples: []Sample{{Type: TypeCPUNanos, StackHash: 1, Value: 300}},+ Samples: []Sample{{Type: "cpu", StackHash: 1, Value: 300}},}d2 := Decoded{Meta: Meta{ServiceName: "api", Start: start, End: start.Add(10 * time.Second)},Stacks: []Stack{{Hash: 2, Frames: []string{"main.main", "main.idle"}}},- Samples: []Sample{{Type: TypeCPUNanos, StackHash: 2, Value: 100}},+ Samples: []Sample{{Type: "cpu", StackHash: 2, Value: 100}},}stacks, samples, profiles := BuildRows(projectId, []Decoded{d1, d2})diff --git a/backend/app/repositories/profile.repository.go b/backend/app/repositories/profile.repository.goindex 0f831c15..cac351a9 100644--- a/backend/app/repositories/profile.repository.go+++ b/backend/app/repositories/profile.repository.go@@ -41,7 +41,7 @@ func (r *profileRepository) InsertSamplesAsync(ctx context.Context, samples []moreturn nil}batch, err := chdb.Conn.PrepareBatch(chdb.BatchCtx(),- "INSERT INTO profiling_samples (project_id, profile_id, service_name, type, start_time, end_time, stack_hash, value, labels, server_name, app_version, trace_id, span_id)")+ "INSERT INTO profiling_samples (project_id, profile_id, service_name, type, unit, is_gauge, start_time, end_time, stack_hash, value, labels, server_name, app_version, trace_id, span_id)")if err != nil {return err}@@ -51,7 +51,7 @@ func (r *profileRepository) InsertSamplesAsync(ctx context.Context, samples []molabels = map[string]string{}}if err := batch.Append(- s.ProjectId, s.ProfileId, s.ServiceName, s.Type, s.Start, s.End,+ s.ProjectId, s.ProfileId, s.ServiceName, s.Type, s.Unit, boolToUInt8(s.IsGauge), s.Start, s.End,s.StackHash, s.Value, labels, s.ServerName, s.AppVersion, s.TraceId, s.SpanId,); err != nil {return err@@ -60,12 +60,19 @@ func (r *profileRepository) InsertSamplesAsync(ctx context.Context, samples []moreturn batch.Send()}+func boolToUInt8(b bool) uint8 {+ if b {+ return 1+ }+ return 0+}+func (r *profileRepository) InsertProfilesAsync(ctx context.Context, profiles []models.Profile) error {if len(profiles) == 0 {return nil}batch, err := chdb.Conn.PrepareBatch(chdb.BatchCtx(),- "INSERT INTO profiles (id, project_id, recorded_at, duration, service_name, profile_type, sample_count, total_value, server_name, app_version, attributes, storage_key, trace_id, span_id, distributed_trace_id)")+ "INSERT INTO profiles (id, project_id, recorded_at, duration, service_name, profile_type, unit, is_gauge, sample_count, total_value, server_name, app_version, attributes, storage_key, trace_id, span_id, distributed_trace_id)")if err != nil {return err}@@ -77,7 +84,7 @@ func (r *profileRepository) InsertProfilesAsync(ctx context.Context, profiles []}}if err := batch.Append(- p.Id, p.ProjectId, p.RecordedAt, int64(p.Duration), p.ServiceName, p.ProfileType,+ p.Id, p.ProjectId, p.RecordedAt, int64(p.Duration), p.ServiceName, p.ProfileType, p.Unit, boolToUInt8(p.IsGauge),p.SampleCount, p.TotalValue, p.ServerName, p.AppVersion, attributesJSON, p.StorageKey,p.TraceId, p.SpanId, p.DistributedTraceId,); err != nil {@@ -87,12 +94,21 @@ func (r *profileRepository) InsertProfilesAsync(ctx context.Context, profiles []return batch.Send()}-func (r *profileRepository) FindGroupedByService(ctx context.Context, projectId uuid.UUID, from, to time.Time, page, pageSize int, orderBy, sortDirection string) ([]models.ProfileGroup, int64, error) {+func (r *profileRepository) FindGroupedByService(ctx context.Context, projectId uuid.UUID, from, to time.Time, page, pageSize int, orderBy, sortDirection, search string) ([]models.ProfileGroup, int64, error) {+ searchClause := ""+ if search != "" {+ searchClause = " AND positionCaseInsensitive(service_name, ?) > 0"+ }++ countArgs := []interface{}{projectId, from, to}+ if search != "" {+ countArgs = append(countArgs, search)+ }var count uint64err := chdb.Conn.QueryRow(ctx,`SELECT count() FROM (SELECT service_name, profile_type FROM profiles- WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?- GROUP BY service_name, profile_type)`, projectId, from, to).Scan(&count)+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?`+searchClause+`+ GROUP BY service_name, profile_type)`, countArgs...).Scan(&count)if err != nil {return nil, 0, err}@@ -114,17 +130,25 @@ func (r *profileRepository) FindGroupedByService(ctx context.Context, projectIdoffset := (page - 1) * pageSizequery := fmt.Sprintf(`SELECT service_name, profile_type,+ any(unit) AS unit,+ max(is_gauge) AS is_gauge,count() AS profile_count,sum(sample_count) AS sample_count,sum(total_value) AS total_value,max(recorded_at) AS last_seenFROM profiles- WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?`+searchClause+`GROUP BY service_name, profile_typeORDER BY %s %sLIMIT ? OFFSET ?`, orderExpr, sortDir)- rows, err := chdb.Conn.Query(ctx, query, projectId, from, to, pageSize, offset)+ pageArgs := []interface{}{projectId, from, to}+ if search != "" {+ pageArgs = append(pageArgs, search)+ }+ pageArgs = append(pageArgs, pageSize, offset)++ rows, err := chdb.Conn.Query(ctx, query, pageArgs...)if err != nil {return nil, 0, err}@@ -134,32 +158,126 @@ func (r *profileRepository) FindGroupedByService(ctx context.Context, projectIdfor rows.Next() {var g models.ProfileGroupvar profileCount, sampleCount uint64- if err := rows.Scan(&g.ServiceName, &g.Type, &profileCount, &sampleCount, &g.TotalValue, &g.LastSeen); err != nil {+ var isGauge uint8+ if err := rows.Scan(&g.ServiceName, &g.Type, &g.Unit, &isGauge, &profileCount, &sampleCount, &g.TotalValue, &g.LastSeen); err != nil {return nil, 0, err}+ g.IsGauge = isGauge != 0g.ProfileCount = int64(profileCount)g.SampleCount = int64(sampleCount)groups = append(groups, g)}++ if err := r.fillSparklines(ctx, projectId, from, to, groups); err != nil {+ return nil, 0, err+ }return groups, int64(count), nil}-func (r *profileRepository) GetSeries(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+func (r *profileRepository) fillSparklines(ctx context.Context, projectId uuid.UUID, from, to time.Time, groups []models.ProfileGroup) error {+ if len(groups) == 0 {+ return nil+ }+ const buckets = 16+ bucketSecs := int(to.Sub(from).Seconds()) / buckets+ if bucketSecs < 1 {+ bucketSecs = 1+ }+ alignedFrom := (from.Unix() / int64(bucketSecs)) * int64(bucketSecs)++ rows, err := chdb.Conn.Query(ctx, `SELECT service_name, profile_type,+ toStartOfInterval(recorded_at, INTERVAL ? SECOND) AS bucket,+ toFloat64(sum(total_value)) AS v+ FROM profiles+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY service_name, profile_type, bucket`, bucketSecs, projectId, from, to)+ if err != nil {+ return err+ }+ defer rows.Close()++ acc := map[string][]float64{}+ for rows.Next() {+ var service, ptype string+ var bucket time.Time+ var v float64+ if err := rows.Scan(&service, &ptype, &bucket, &v); err != nil {+ return err+ }+ idx := int((bucket.Unix() - alignedFrom) / int64(bucketSecs))+ if idx < 0 {+ idx = 0+ }+ if idx >= buckets {+ idx = buckets - 1+ }+ key := service + "\x00" + ptype+ arr, ok := acc[key]+ if !ok {+ arr = make([]float64, buckets)+ acc[key] = arr+ }+ arr[idx] += v+ }++ for i := range groups {+ if arr, ok := acc[groups[i].ServiceName+"\x00"+groups[i].Type]; ok {+ groups[i].Sparkline = arr+ } else {+ groups[i].Sparkline = []float64{}+ }+ }+ return nil+}++func (r *profileRepository) DiscoverTypes(ctx context.Context, projectId uuid.UUID, service string, from, to time.Time) ([]models.ProfileTypeInfo, error) {+ rows, err := chdb.Conn.Query(ctx,+ `SELECT type, any(unit) AS unit, max(is_gauge) AS is_gauge+ FROM profiling_samples+ WHERE project_id = ? AND service_name = ? AND start_time >= ? AND start_time <= ?+ GROUP BY type+ ORDER BY type ASC`, projectId, service, from, to)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var out []models.ProfileTypeInfo+ for rows.Next() {+ var info models.ProfileTypeInfo+ var isGauge uint8+ if err := rows.Scan(&info.Type, &info.Unit, &isGauge); err != nil {+ return nil, err+ }+ info.IsGauge = isGauge != 0+ out = append(out, info)+ }+ return out, nil+}++func (r *profileRepository) GetSeries(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, intervalMinutes int, isGauge bool, labelFilters map[string]string, appVersion, serverName string, normalize bool) ([]models.TimeSeriesPoint, error) {if intervalMinutes < 1 {intervalMinutes = 1}agg := "sum"- if profiling.IsGauge(profileType) {+ if isGauge {agg = "avg"}+ filter, filterArgs := chLabelFilter("", labelFilters)+ cohort, cohortArgs := chCohortFilter("", appVersion, serverName)+query := fmt.Sprintf(`SELECT toStartOfInterval(start_time, INTERVAL ? MINUTE) AS bucket,toFloat64(%s(value)) AS agg_valueFROM profiling_samples- WHERE project_id = ? AND type = ? AND service_name = ? AND start_time >= ? AND start_time <= ?+ WHERE project_id = ? AND type = ? AND service_name = ? AND start_time >= ? AND start_time <= ?`+filter+cohort+`GROUP BY bucket ORDER BY bucket ASC`, agg)- rows, err := chdb.Conn.Query(ctx, query, intervalMinutes, projectId, profileType, service, from, to)+ args := []interface{}{intervalMinutes, projectId, profileType, service, from, to}+ args = append(args, filterArgs...)+ args = append(args, cohortArgs...)++ rows, err := chdb.Conn.Query(ctx, query, args...)if err != nil {return nil, err}@@ -173,40 +291,48 @@ func (r *profileRepository) GetSeries(ctx context.Context, projectId uuid.UUID,}points = append(points, p)}+ normalizeSeriesPoints(points, normalize, isGauge, intervalMinutes)return points, nil}-func (r *profileRepository) GetFlameGraph(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, labelFilters map[string]string) ([]models.ProfileStackValue, error) {+func (r *profileRepository) GetFlameGraph(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, labelFilters map[string]string, isGauge bool, appVersion, serverName string) ([]models.ProfileStackValue, error) {bareFilter, bareArgs := chLabelFilter("", labelFilters)aliasFilter, aliasArgs := chLabelFilter("s.", labelFilters)+ bareCohort, bareCohortArgs := chCohortFilter("", appVersion, serverName)+ aliasCohort, aliasCohortArgs := chCohortFilter("s.", appVersion, serverName)var query stringvar args []interface{}- if profiling.IsGauge(profileType) {+ if isGauge {query = `WITH latest AS (SELECT argMax(profile_id, start_time) AS pid FROM profiling_samples- WHERE project_id = ? AND type = ? AND service_name = ? AND start_time >= ? AND start_time <= ?` + bareFilter + `+ WHERE project_id = ? AND type = ? AND service_name = ? AND start_time >= ? AND start_time <= ?` + bareFilter + bareCohort + `GROUP BY server_name)SELECT st.stack, sum(s.value) AS vFROM profiling_samples sINNER JOIN latest l ON l.pid = s.profile_idINNER JOIN ` + profileStackDedup + ` st ON st.project_id = s.project_id AND st.service_name = s.service_name AND st.stack_hash = s.stack_hash- WHERE s.project_id = ? AND s.type = ? AND s.service_name = ? AND s.start_time >= ? AND s.start_time <= ?` + aliasFilter + `- GROUP BY s.stack_hash, st.stack`+ WHERE s.project_id = ? AND s.type = ? AND s.service_name = ? AND s.start_time >= ? AND s.start_time <= ?` + aliasFilter + aliasCohort + `+ GROUP BY s.stack_hash, st.stack+ ORDER BY v DESC LIMIT 50000`args = append(args, projectId, profileType, service, from, to)args = append(args, bareArgs...)+ args = append(args, bareCohortArgs...)args = append(args, projectId, service)args = append(args, projectId, profileType, service, from, to)args = append(args, aliasArgs...)+ args = append(args, aliasCohortArgs...)} else {query = `SELECT st.stack, sum(s.value) AS vFROM profiling_samples sINNER JOIN ` + profileStackDedup + ` st ON st.project_id = s.project_id AND st.service_name = s.service_name AND st.stack_hash = s.stack_hash- WHERE s.project_id = ? AND s.type = ? AND s.service_name = ? AND s.start_time >= ? AND s.start_time <= ?` + aliasFilter + `- GROUP BY s.stack_hash, st.stack`+ WHERE s.project_id = ? AND s.type = ? AND s.service_name = ? AND s.start_time >= ? AND s.start_time <= ?` + aliasFilter + aliasCohort + `+ GROUP BY s.stack_hash, st.stack+ ORDER BY v DESC LIMIT 50000`args = append(args, projectId, service)args = append(args, projectId, profileType, service, from, to)args = append(args, aliasArgs...)+ args = append(args, aliasCohortArgs...)}rows, err := chdb.Conn.Query(ctx, query, args...)@@ -252,6 +378,158 @@ func (r *profileRepository) distinctLabelValues(ctx context.Context, projectId ureturn values, nil}+func (r *profileRepository) GetSeriesBreakdown(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, intervalMinutes int, isGauge bool, labelFilters map[string]string, appVersion, serverName string, normalize bool, dimension string, limit int) ([]models.ProfileSeriesGroup, error) {+ if intervalMinutes < 1 {+ intervalMinutes = 1+ }+ limit = clampBreakdownLimit(limit)+ agg := "sum"+ if isGauge {+ agg = "avg"+ }++ filter, filterArgs := chLabelFilter("", labelFilters)+ cohort, cohortArgs := chCohortFilter("", appVersion, serverName)+ dimExpr, dimArgs, ok := chDimExpr(dimension)+ if !ok {+ return nil, fmt.Errorf("unsupported breakdown dimension: %s", dimension)+ }++ topQuery := fmt.Sprintf(`SELECT %s AS k, toFloat64(%s(value)) AS tv+ FROM profiling_samples+ WHERE project_id = ? AND type = ? AND service_name = ? AND start_time >= ? AND start_time <= ?`+filter+cohort+`+ AND %s != ''+ GROUP BY k ORDER BY tv DESC LIMIT ?`, dimExpr, agg, dimExpr)++ var topArgs []interface{}+ topArgs = append(topArgs, dimArgs...)+ topArgs = append(topArgs, projectId, profileType, service, from, to)+ topArgs = append(topArgs, filterArgs...)+ topArgs = append(topArgs, cohortArgs...)+ topArgs = append(topArgs, dimArgs...)+ topArgs = append(topArgs, limit)++ rows, err := chdb.Conn.Query(ctx, topQuery, topArgs...)+ if err != nil {+ return nil, err+ }+ var keys []string+ for rows.Next() {+ var k string+ var tv float64+ if err := rows.Scan(&k, &tv); err != nil {+ rows.Close()+ return nil, err+ }+ keys = append(keys, k)+ }+ rows.Close()+ if err := rows.Err(); err != nil {+ return nil, err+ }++ seriesQuery := fmt.Sprintf(`SELECT toStartOfInterval(start_time, INTERVAL ? MINUTE) AS bucket,+ toFloat64(%s(value)) AS agg_value+ FROM profiling_samples+ WHERE project_id = ? AND type = ? AND service_name = ? AND start_time >= ? AND start_time <= ?`+filter+cohort+`+ AND %s = ?+ GROUP BY bucket ORDER BY bucket ASC`, agg, dimExpr)++ groups := make([]models.ProfileSeriesGroup, 0, len(keys))+ for _, key := range keys {+ var seriesArgs []interface{}+ seriesArgs = append(seriesArgs, intervalMinutes, projectId, profileType, service, from, to)+ seriesArgs = append(seriesArgs, filterArgs...)+ seriesArgs = append(seriesArgs, cohortArgs...)+ seriesArgs = append(seriesArgs, dimArgs...)+ seriesArgs = append(seriesArgs, key)++ srows, err := chdb.Conn.Query(ctx, seriesQuery, seriesArgs...)+ if err != nil {+ return nil, err+ }+ var points []models.TimeSeriesPoint+ for srows.Next() {+ var p models.TimeSeriesPoint+ if err := srows.Scan(&p.Timestamp, &p.Value); err != nil {+ srows.Close()+ return nil, err+ }+ points = append(points, p)+ }+ srows.Close()+ if err := srows.Err(); err != nil {+ return nil, err+ }+ normalizeSeriesPoints(points, normalize, isGauge, intervalMinutes)+ groups = append(groups, models.ProfileSeriesGroup{Key: key, Points: points})+ }+ return groups, nil+}++func (r *profileRepository) DiscoverDimensions(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time) ([]string, []string, error) {+ appVersions, err := r.distinctDimensionValues(ctx, projectId, service, profileType, "app_version", from, to)+ if err != nil {+ return nil, nil, err+ }+ serverNames, err := r.distinctDimensionValues(ctx, projectId, service, profileType, "server_name", from, to)+ if err != nil {+ return nil, nil, err+ }+ return appVersions, serverNames, nil+}++func (r *profileRepository) distinctDimensionValues(ctx context.Context, projectId uuid.UUID, service, profileType, column string, from, to time.Time) ([]string, error) {+ rows, err := chdb.Conn.Query(ctx,+ fmt.Sprintf(`SELECT DISTINCT %s AS v+ FROM profiling_samples+ WHERE project_id = ? AND service_name = ? AND type = ? AND start_time >= ? AND start_time <= ? AND %s != ''+ ORDER BY %s ASC LIMIT 100`, column, column, column),+ projectId, service, profileType, from, to)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ values := make([]string, 0)+ for rows.Next() {+ var v string+ if err := rows.Scan(&v); err != nil {+ return nil, err+ }+ values = append(values, v)+ }+ return values, rows.Err()+}++func chCohortFilter(qualifier, appVersion, serverName string) (string, []interface{}) {+ clause := ""+ var args []interface{}+ if appVersion != "" {+ clause += fmt.Sprintf(" AND %sapp_version = ?", qualifier)+ args = append(args, appVersion)+ }+ if serverName != "" {+ clause += fmt.Sprintf(" AND %sserver_name = ?", qualifier)+ args = append(args, serverName)+ }+ return clause, args+}++func chDimExpr(dimension string) (string, []interface{}, bool) {+ switch dimension {+ case "app_version":+ return "app_version", nil, true+ case "server_name":+ return "server_name", nil, true+ }+ key, ok := breakdownLabelKey(dimension)+ if !ok || key == "" {+ return "", nil, false+ }+ return "labels[?]", []interface{}{key}, true+}+func chLabelFilter(qualifier string, filters map[string]string) (string, []interface{}) {if len(filters) == 0 {return "", nildiff --git a/backend/app/repositories/profile.repository_common.go b/backend/app/repositories/profile.repository_common.gonew file mode 100644index 00000000..09d0ca2a--- /dev/null+++ b/backend/app/repositories/profile.repository_common.go@@ -0,0 +1,38 @@+package repositories++import (+ "strings"++ "github.com/tracewayapp/traceway/backend/app/models"+)++func normalizeSeriesPoints(points []models.TimeSeriesPoint, normalize, isGauge bool, intervalMinutes int) {+ if !normalize || isGauge {+ return+ }+ secs := intervalMinutes * 60+ if secs < 1 {+ secs = 1+ }+ for i := range points {+ points[i].Value = points[i].Value / float64(secs)+ }+}++func clampBreakdownLimit(limit int) int {+ if limit <= 0 {+ return 8+ }+ if limit > 20 {+ return 20+ }+ return limit+}++func breakdownLabelKey(dimension string) (string, bool) {+ const prefix = "label:"+ if !strings.HasPrefix(dimension, prefix) {+ return "", false+ }+ return strings.TrimPrefix(dimension, prefix), true+}diff --git a/backend/app/repositories/profile.repository_sqlite.go b/backend/app/repositories/profile.repository_sqlite.goindex 16c6c9c0..439d6e03 100644--- a/backend/app/repositories/profile.repository_sqlite.go+++ b/backend/app/repositories/profile.repository_sqlite.go@@ -19,6 +19,8 @@ import (type profileGroupRow struct {ServiceName string `lit:"service_name"`ProfileType string `lit:"profile_type"`+ Unit string `lit:"unit"`+ IsGauge int64 `lit:"is_gauge"`ProfileCount int64 `lit:"profile_count"`SampleCount int64 `lit:"sample_count"`TotalValue int64 `lit:"total_value"`@@ -29,15 +31,35 @@ type labelValueRow struct {Value string `lit:"v"`}+type profileTypeRow struct {+ Type string `lit:"type"`+ Unit string `lit:"unit"`+ IsGauge int64 `lit:"is_gauge"`+}++type profileDimValueRow struct {+ Key *string `lit:"k"`+ Total float64 `lit:"tv"`+}+func init() {models.ExtensionModelRegistrations = append(models.ExtensionModelRegistrations, func(driver lit.Driver) {lit.RegisterModel[profileGroupRow](driver)lit.RegisterModel[labelValueRow](driver)+ lit.RegisterModel[profileTypeRow](driver)+ lit.RegisterModel[profileDimValueRow](driver)})}type profileRepository struct{}+func boolToInt(b bool) int64 {+ if b {+ return 1+ }+ return 0+}+func (r *profileRepository) InsertStacksAsync(ctx context.Context, stacks []models.ProfileStack) error {if len(stacks) == 0 {return nil@@ -85,12 +107,14 @@ func (r *profileRepository) InsertSamplesAsync(ctx context.Context, samples []mofor _, s := range samples {labelsVal, _ := NewSQLiteJSONMap(s.Labels).Value()query, args, err := lit.ParseNamedQuery(db.Driver,- "INSERT INTO profiling_samples (project_id, profile_id, service_name, type, start_time, end_time, stack_hash, value, labels, server_name, app_version, trace_id, span_id) VALUES (:project_id, :profile_id, :service_name, :type, :start_time, :end_time, :stack_hash, :value, :labels, :server_name, :app_version, :trace_id, :span_id)",+ "INSERT INTO profiling_samples (project_id, profile_id, service_name, type, unit, is_gauge, start_time, end_time, stack_hash, value, labels, server_name, app_version, trace_id, span_id) VALUES (:project_id, :profile_id, :service_name, :type, :unit, :is_gauge, :start_time, :end_time, :stack_hash, :value, :labels, :server_name, :app_version, :trace_id, :span_id)",lit.P{"project_id": s.ProjectId,"profile_id": s.ProfileId,"service_name": s.ServiceName,"type": s.Type,+ "unit": s.Unit,+ "is_gauge": boolToInt(s.IsGauge),"start_time": NewSQLiteTime(s.Start),"end_time": NewSQLiteTime(s.End),"stack_hash": int64(s.StackHash),@@ -124,7 +148,7 @@ func (r *profileRepository) InsertProfilesAsync(ctx context.Context, profiles []for _, p := range profiles {attributesVal, _ := NewSQLiteJSONMap(p.Attributes).Value()query, args, err := lit.ParseNamedQuery(db.Driver,- "INSERT INTO profiles (id, project_id, recorded_at, duration, service_name, profile_type, sample_count, total_value, server_name, app_version, attributes, storage_key, trace_id, span_id, distributed_trace_id) VALUES (:id, :project_id, :recorded_at, :duration, :service_name, :profile_type, :sample_count, :total_value, :server_name, :app_version, :attributes, :storage_key, :trace_id, :span_id, :distributed_trace_id)",+ "INSERT INTO profiles (id, project_id, recorded_at, duration, service_name, profile_type, unit, is_gauge, sample_count, total_value, server_name, app_version, attributes, storage_key, trace_id, span_id, distributed_trace_id) VALUES (:id, :project_id, :recorded_at, :duration, :service_name, :profile_type, :unit, :is_gauge, :sample_count, :total_value, :server_name, :app_version, :attributes, :storage_key, :trace_id, :span_id, :distributed_trace_id)",lit.P{"id": p.Id,"project_id": p.ProjectId,@@ -132,6 +156,8 @@ func (r *profileRepository) InsertProfilesAsync(ctx context.Context, profiles []"duration": int64(p.Duration),"service_name": p.ServiceName,"profile_type": p.ProfileType,+ "unit": p.Unit,+ "is_gauge": boolToInt(p.IsGauge),"sample_count": int64(p.SampleCount),"total_value": p.TotalValue,"server_name": p.ServerName,@@ -152,14 +178,19 @@ func (r *profileRepository) InsertProfilesAsync(ctx context.Context, profiles []return tx.Commit()}-func (r *profileRepository) FindGroupedByService(ctx context.Context, projectId uuid.UUID, from, to time.Time, page, pageSize int, orderBy, sortDirection string) ([]models.ProfileGroup, int64, error) {- params := lit.P{"project_id": projectId, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)}+func (r *profileRepository) FindGroupedByService(ctx context.Context, projectId uuid.UUID, from, to time.Time, page, pageSize int, orderBy, sortDirection, search string) ([]models.ProfileGroup, int64, error) {+ searchClause := ""+ countParams := lit.P{"project_id": projectId, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)}+ if search != "" {+ searchClause = " AND instr(lower(service_name), lower(:search)) > 0"+ countParams["search"] = search+ }countResult, err := lit.SelectSingleNamed[models.CountResult](db.TelemetryDB,`SELECT COUNT(*) AS count FROM (SELECT 1 FROM profiles- WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to- GROUP BY service_name, profile_type)`, params)+ WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to`+searchClause+`+ GROUP BY service_name, profile_type)`, countParams)if err != nil {return nil, 0, err}@@ -184,18 +215,24 @@ func (r *profileRepository) FindGroupedByService(ctx context.Context, projectId}offset := (page - 1) * pageSize+ pageParams := lit.P{"project_id": projectId, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to), "limit": pageSize, "offset": offset}+ if search != "" {+ pageParams["search"] = search+ }rows, err := lit.SelectNamed[profileGroupRow](db.TelemetryDB,fmt.Sprintf(`SELECT service_name, profile_type,+ MAX(unit) AS unit,+ MAX(is_gauge) AS is_gauge,COUNT(*) AS profile_count,SUM(sample_count) AS sample_count,SUM(total_value) AS total_value,MAX(recorded_at) AS last_seenFROM profiles- WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to`+searchClause+`GROUP BY service_name, profile_typeORDER BY %s %sLIMIT :limit OFFSET :offset`, orderExpr, sortDir),- lit.P{"project_id": projectId, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to), "limit": pageSize, "offset": offset})+ pageParams)if err != nil {return nil, 0, err}@@ -205,66 +242,167 @@ func (r *profileRepository) FindGroupedByService(ctx context.Context, projectIdgroups = append(groups, models.ProfileGroup{ServiceName: row.ServiceName,Type: row.ProfileType,+ Unit: row.Unit,+ IsGauge: row.IsGauge != 0,ProfileCount: row.ProfileCount,SampleCount: row.SampleCount,TotalValue: row.TotalValue,LastSeen: row.LastSeen.Time,})}++ if err := r.fillSparklines(ctx, projectId, from, to, groups); err != nil {+ return nil, 0, err+ }return groups, total, nil}-func (r *profileRepository) GetSeries(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+func (r *profileRepository) fillSparklines(ctx context.Context, projectId uuid.UUID, from, to time.Time, groups []models.ProfileGroup) error {+ if len(groups) == 0 {+ return nil+ }+ const buckets = 16+ bucketSecs := int(to.Sub(from).Seconds()) / buckets+ if bucketSecs < 1 {+ bucketSecs = 1+ }+ alignedFrom := (from.Unix() / int64(bucketSecs)) * int64(bucketSecs)++ query, args, err := lit.ParseNamedQuery(db.Driver,+ fmt.Sprintf(`SELECT service_name, profile_type,+ CAST((strftime('%%s', recorded_at) / %d) * %d AS INTEGER) AS bucket,+ CAST(SUM(total_value) AS REAL) AS v+ FROM profiles+ WHERE project_id = :project_id AND recorded_at >= :from AND recorded_at <= :to+ GROUP BY service_name, profile_type, bucket`, bucketSecs, bucketSecs),+ lit.P{"project_id": projectId, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)})+ if err != nil {+ return err+ }+ sqlRows, err := db.TelemetryDB.QueryContext(ctx, query, args...)+ if err != nil {+ return err+ }+ defer sqlRows.Close()++ acc := map[string][]float64{}+ for sqlRows.Next() {+ var service, ptype string+ var bucketEpoch int64+ var v float64+ if err := sqlRows.Scan(&service, &ptype, &bucketEpoch, &v); err != nil {+ return err+ }+ idx := int((bucketEpoch - alignedFrom) / int64(bucketSecs))+ if idx < 0 {+ idx = 0+ }+ if idx >= buckets {+ idx = buckets - 1+ }+ key := service + "\x00" + ptype+ arr, ok := acc[key]+ if !ok {+ arr = make([]float64, buckets)+ acc[key] = arr+ }+ arr[idx] += v+ }+ if err := sqlRows.Err(); err != nil {+ return err+ }++ for i := range groups {+ if arr, ok := acc[groups[i].ServiceName+"\x00"+groups[i].Type]; ok {+ groups[i].Sparkline = arr+ } else {+ groups[i].Sparkline = []float64{}+ }+ }+ return nil+}++func (r *profileRepository) DiscoverTypes(ctx context.Context, projectId uuid.UUID, service string, from, to time.Time) ([]models.ProfileTypeInfo, error) {+ rows, err := lit.SelectNamed[profileTypeRow](db.TelemetryDB,+ `SELECT type, MAX(unit) AS unit, MAX(is_gauge) AS is_gauge+ FROM profiling_samples+ WHERE project_id = :project_id AND service_name = :service+ AND start_time >= :from AND start_time <= :to+ GROUP BY type+ ORDER BY type ASC`,+ lit.P{"project_id": projectId, "service": service, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)})+ if err != nil {+ return nil, err+ }++ out := make([]models.ProfileTypeInfo, 0, len(rows))+ for _, row := range rows {+ out = append(out, models.ProfileTypeInfo{Type: row.Type, Unit: row.Unit, IsGauge: row.IsGauge != 0})+ }+ return out, nil+}++func (r *profileRepository) GetSeries(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, intervalMinutes int, isGauge bool, labelFilters map[string]string, appVersion, serverName string, normalize bool) ([]models.TimeSeriesPoint, error) {if intervalMinutes < 1 {intervalMinutes = 1}secs := intervalMinutes * 60agg := "SUM"- if profiling.IsGauge(profileType) {+ if isGauge {agg = "AVG"}+ params := lit.P{"project_id": projectId, "type": profileType, "service": service, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)}+ filter := sqliteLabelFilter("", labelFilters, params)+ cohort := sqliteCohortFilter("", appVersion, serverName, params)+results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB,fmt.Sprintf(`SELECT datetime((strftime('%%s', start_time) / %d) * %d, 'unixepoch') AS bucket,CAST(%s(value) AS REAL) AS agg_valueFROM profiling_samplesWHERE project_id = :project_id AND type = :type AND service_name = :service- AND start_time >= :from AND start_time <= :to+ AND start_time >= :from AND start_time <= :to`+filter+cohort+`GROUP BY bucket ORDER BY bucket ASC`, secs, secs, agg),- lit.P{"project_id": projectId, "type": profileType, "service": service, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)})+ params)if err != nil {return nil, err}- return timeSeriesResultsToPoints(results), nil+ points := timeSeriesResultsToPoints(results)+ normalizeSeriesPoints(points, normalize, isGauge, intervalMinutes)+ return points, nil}-func (r *profileRepository) GetFlameGraph(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, labelFilters map[string]string) ([]models.ProfileStackValue, error) {+func (r *profileRepository) GetFlameGraph(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, labelFilters map[string]string, isGauge bool, appVersion, serverName string) ([]models.ProfileStackValue, error) {params := lit.P{"project_id": projectId, "type": profileType, "service": service, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)}bareFilter := sqliteLabelFilter("", labelFilters, params)aliasFilter := sqliteLabelFilter("s.", labelFilters, params)+ bareCohort := sqliteCohortFilter("", appVersion, serverName, params)+ aliasCohort := sqliteCohortFilter("s.", appVersion, serverName, params)var query string- if profiling.IsGauge(profileType) {+ if isGauge {query = `WITH latest AS (SELECT profile_id AS pid, MAX(start_time) AS mxFROM profiling_samplesWHERE project_id = :project_id AND type = :type AND service_name = :service- AND start_time >= :from AND start_time <= :to` + bareFilter + `+ AND start_time >= :from AND start_time <= :to` + bareFilter + bareCohort + `GROUP BY server_name)SELECT st.stack AS stack_json, CAST(SUM(s.value) AS INTEGER) AS vFROM profiling_samples sJOIN latest l ON l.pid = s.profile_idJOIN profiling_stacks st ON st.project_id = s.project_id AND st.service_name = s.service_name AND st.stack_hash = s.stack_hashWHERE s.project_id = :project_id AND s.type = :type AND s.service_name = :service- AND s.start_time >= :from AND s.start_time <= :to` + aliasFilter + `- GROUP BY s.stack_hash, st.stack`+ AND s.start_time >= :from AND s.start_time <= :to` + aliasFilter + aliasCohort + `+ GROUP BY s.stack_hash, st.stack+ ORDER BY v DESC LIMIT 50000`} else {query = `SELECT st.stack AS stack_json, CAST(SUM(s.value) AS INTEGER) AS vFROM profiling_samples sJOIN profiling_stacks st ON st.project_id = s.project_id AND st.service_name = s.service_name AND st.stack_hash = s.stack_hashWHERE s.project_id = :project_id AND s.type = :type AND s.service_name = :service- AND s.start_time >= :from AND s.start_time <= :to` + aliasFilter + `- GROUP BY s.stack_hash, st.stack`+ AND s.start_time >= :from AND s.start_time <= :to` + aliasFilter + aliasCohort + `+ GROUP BY s.stack_hash, st.stack+ ORDER BY v DESC LIMIT 50000`}parsed, args, err := lit.ParseNamedQuery(db.Driver, query, params)@@ -315,6 +453,121 @@ func (r *profileRepository) distinctLabelValues(ctx context.Context, projectId ureturn values, nil}+func (r *profileRepository) GetSeriesBreakdown(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time, intervalMinutes int, isGauge bool, labelFilters map[string]string, appVersion, serverName string, normalize bool, dimension string, limit int) ([]models.ProfileSeriesGroup, error) {+ if intervalMinutes < 1 {+ intervalMinutes = 1+ }+ secs := intervalMinutes * 60+ limit = clampBreakdownLimit(limit)+ agg := "SUM"+ if isGauge {+ agg = "AVG"+ }++ params := lit.P{"project_id": projectId, "type": profileType, "service": service, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to), "limit": limit}+ filter := sqliteLabelFilter("", labelFilters, params)+ cohort := sqliteCohortFilter("", appVersion, serverName, params)+ dimExpr, ok := sqliteDimExpr(dimension, params)+ if !ok {+ return nil, fmt.Errorf("unsupported breakdown dimension: %s", dimension)+ }++ topRows, err := lit.SelectNamed[profileDimValueRow](db.TelemetryDB,+ fmt.Sprintf(`SELECT %s AS k, CAST(%s(value) AS REAL) AS tv+ FROM profiling_samples+ WHERE project_id = :project_id AND type = :type AND service_name = :service+ AND start_time >= :from AND start_time <= :to`+filter+cohort+`+ AND %s != ''+ GROUP BY k ORDER BY tv DESC LIMIT :limit`, dimExpr, agg, dimExpr),+ params)+ if err != nil {+ return nil, err+ }++ seriesQuery := fmt.Sprintf(`SELECT datetime((strftime('%%s', start_time) / %d) * %d, 'unixepoch') AS bucket,+ CAST(%s(value) AS REAL) AS agg_value+ FROM profiling_samples+ WHERE project_id = :project_id AND type = :type AND service_name = :service+ AND start_time >= :from AND start_time <= :to`+filter+cohort+`+ AND %s = :dimval+ GROUP BY bucket ORDER BY bucket ASC`, secs, secs, agg, dimExpr)++ groups := make([]models.ProfileSeriesGroup, 0, len(topRows))+ for _, row := range topRows {+ if row.Key == nil {+ continue+ }+ key := *row.Key+ params["dimval"] = key+ results, err := lit.SelectNamed[timeSeriesResult](db.TelemetryDB, seriesQuery, params)+ if err != nil {+ return nil, err+ }+ points := timeSeriesResultsToPoints(results)+ normalizeSeriesPoints(points, normalize, isGauge, intervalMinutes)+ groups = append(groups, models.ProfileSeriesGroup{Key: key, Points: points})+ }+ return groups, nil+}++func (r *profileRepository) DiscoverDimensions(ctx context.Context, projectId uuid.UUID, service, profileType string, from, to time.Time) ([]string, []string, error) {+ appVersions, err := r.distinctDimensionValues(ctx, projectId, service, profileType, "app_version", from, to)+ if err != nil {+ return nil, nil, err+ }+ serverNames, err := r.distinctDimensionValues(ctx, projectId, service, profileType, "server_name", from, to)+ if err != nil {+ return nil, nil, err+ }+ return appVersions, serverNames, nil+}++func (r *profileRepository) distinctDimensionValues(ctx context.Context, projectId uuid.UUID, service, profileType, column string, from, to time.Time) ([]string, error) {+ rows, err := lit.SelectNamed[labelValueRow](db.TelemetryDB,+ fmt.Sprintf(`SELECT DISTINCT %s AS v+ FROM profiling_samples+ WHERE project_id = :project_id AND service_name = :service AND type = :type+ AND start_time >= :from AND start_time <= :to AND %s != ''+ ORDER BY %s ASC LIMIT 100`, column, column, column),+ lit.P{"project_id": projectId, "service": service, "type": profileType, "from": NewSQLiteTime(from), "to": NewSQLiteTime(to)})+ if err != nil {+ return nil, err+ }+ values := make([]string, 0, len(rows))+ for _, row := range rows {+ values = append(values, row.Value)+ }+ return values, nil+}++func sqliteCohortFilter(qualifier, appVersion, serverName string, params lit.P) string {+ clause := ""+ if appVersion != "" {+ clause += fmt.Sprintf(" AND %sapp_version = :app_version", qualifier)+ params["app_version"] = appVersion+ }+ if serverName != "" {+ clause += fmt.Sprintf(" AND %sserver_name = :server_name", qualifier)+ params["server_name"] = serverName+ }+ return clause+}++func sqliteDimExpr(dimension string, params lit.P) (string, bool) {+ switch dimension {+ case "app_version":+ return "app_version", true+ case "server_name":+ return "server_name", true+ }+ key, ok := breakdownLabelKey(dimension)+ if !ok || key == "" {+ return "", false+ }+ params["dimpath"] = "$.\"" + key + "\""+ return "json_extract(labels, :dimpath)", true+}+func sqliteLabelFilter(qualifier string, filters map[string]string, params lit.P) string {if len(filters) == 0 {return ""diff --git a/backend/app/repositories/profile_labels_test.go b/backend/app/repositories/profile_labels_test.goindex 154c2d2a..742f7e60 100644--- a/backend/app/repositories/profile_labels_test.go+++ b/backend/app/repositories/profile_labels_test.go@@ -29,16 +29,16 @@ func TestProfileRepository_DiscoverLabels(t *testing.T) {}}mustInsertSamples(t, ctx,- sample(base, "checkout", profiling.TypeCPUNanos, map[string]string{"endpoint": "/a"}),- sample(base, "checkout", profiling.TypeCPUNanos, map[string]string{"endpoint": "/b"}),- sample(base, "checkout", profiling.TypeCPUNanos, map[string]string{"endpoint": "/a"}),- sample(base, "checkout", profiling.TypeCPUNanos, map[string]string{"endpoint": "", "region": "us"}),- sample(base.Add(-2*time.Hour), "checkout", profiling.TypeCPUNanos, map[string]string{"endpoint": "/before"}),- sample(base, "billing", profiling.TypeCPUNanos, map[string]string{"endpoint": "/other-service"}),- sample(base, "checkout", profiling.TypeHeapInuseSpace, map[string]string{"endpoint": "/other-type"}),+ sample(base, "checkout", "cpu", map[string]string{"endpoint": "/a"}),+ sample(base, "checkout", "cpu", map[string]string{"endpoint": "/b"}),+ sample(base, "checkout", "cpu", map[string]string{"endpoint": "/a"}),+ sample(base, "checkout", "cpu", map[string]string{"endpoint": "", "region": "us"}),+ sample(base.Add(-2*time.Hour), "checkout", "cpu", map[string]string{"endpoint": "/before"}),+ sample(base, "billing", "cpu", map[string]string{"endpoint": "/other-service"}),+ sample(base, "checkout", "inuse_space", map[string]string{"endpoint": "/other-type"}),)- labels, err := ProfileRepository.DiscoverLabels(ctx, projectId, "checkout", profiling.TypeCPUNanos, from, to, profiling.LabelAllowKeys(nil))+ labels, err := ProfileRepository.DiscoverLabels(ctx, projectId, "checkout", "cpu", from, to, profiling.LabelAllowKeys(nil))if err != nil {t.Fatalf("DiscoverLabels: %v", err)}@@ -64,12 +64,12 @@ func TestProfileRepository_DiscoverLabels_NoValuesOmitsKey(t *testing.T) {mustInsertSamples(t, ctx,models.ProfileSample{ProjectId: projectId, ProfileId: uuid.New(), ServiceName: "checkout",- Type: profiling.TypeCPUNanos, Start: base, End: base, StackHash: hashX, Value: 1,+ Type: "cpu", Start: base, End: base, StackHash: hashX, Value: 1,Labels: map[string]string{"endpoint": ""},},)- labels, err := ProfileRepository.DiscoverLabels(ctx, projectId, "checkout", profiling.TypeCPUNanos, from, to, profiling.LabelAllowKeys(nil))+ labels, err := ProfileRepository.DiscoverLabels(ctx, projectId, "checkout", "cpu", from, to, profiling.LabelAllowKeys(nil))if err != nil {t.Fatalf("DiscoverLabels: %v", err)}@@ -90,7 +90,7 @@ func TestProfileRepository_DiscoverLabels_DottedKey(t *testing.T) {sample := func(labels map[string]string) models.ProfileSample {return models.ProfileSample{ProjectId: projectId, ProfileId: uuid.New(), ServiceName: "checkout",- Type: profiling.TypeCPUNanos, Start: base, End: base, StackHash: hashX, Value: 1, Labels: labels,+ Type: "cpu", Start: base, End: base, StackHash: hashX, Value: 1, Labels: labels,}}mustInsertSamples(t, ctx,@@ -98,7 +98,7 @@ func TestProfileRepository_DiscoverLabels_DottedKey(t *testing.T) {sample(map[string]string{"endpoint": "/y", "http.route": "GET /cart"}),)- labels, err := ProfileRepository.DiscoverLabels(ctx, projectId, "checkout", profiling.TypeCPUNanos, from, to, profiling.LabelAllowKeys([]string{"http.route"}))+ labels, err := ProfileRepository.DiscoverLabels(ctx, projectId, "checkout", "cpu", from, to, profiling.LabelAllowKeys([]string{"http.route"}))if err != nil {t.Fatalf("DiscoverLabels: %v", err)}@@ -122,13 +122,13 @@ func TestProfileRepository_DiscoverLabels_LimitsValuesPerKey(t *testing.T) {for i := range total {samples = append(samples, models.ProfileSample{ProjectId: projectId, ProfileId: uuid.New(), ServiceName: "checkout",- Type: profiling.TypeCPUNanos, Start: base, End: base, StackHash: hashX, Value: 1,+ Type: "cpu", Start: base, End: base, StackHash: hashX, Value: 1,Labels: map[string]string{"endpoint": fmt.Sprintf("/e%05d", i)},})}mustInsertSamples(t, ctx, samples...)- labels, err := ProfileRepository.DiscoverLabels(ctx, projectId, "checkout", profiling.TypeCPUNanos, from, to, profiling.LabelAllowKeys(nil))+ labels, err := ProfileRepository.DiscoverLabels(ctx, projectId, "checkout", "cpu", from, to, profiling.LabelAllowKeys(nil))if err != nil {t.Fatalf("DiscoverLabels: %v", err)}diff --git a/backend/app/repositories/profile_query_test.go b/backend/app/repositories/profile_query_test.goindex 00795661..e44a21d4 100644--- a/backend/app/repositories/profile_query_test.go+++ b/backend/app/repositories/profile_query_test.go@@ -57,12 +57,12 @@ func TestProfileRepository_FindGroupedByService(t *testing.T) {to := base.Add(time.Hour)mustInsertProfiles(t, ctx,- models.Profile{Id: uuid.New(), ProjectId: projectId, RecordedAt: base, ServiceName: "checkout", ProfileType: profiling.TypeCPUNanos, SampleCount: 2, TotalValue: 300},- models.Profile{Id: uuid.New(), ProjectId: projectId, RecordedAt: base.Add(time.Minute), ServiceName: "checkout", ProfileType: profiling.TypeCPUNanos, SampleCount: 1, TotalValue: 200},- models.Profile{Id: uuid.New(), ProjectId: projectId, RecordedAt: base, ServiceName: "checkout", ProfileType: profiling.TypeHeapInuseSpace, SampleCount: 3, TotalValue: 9000},+ models.Profile{Id: uuid.New(), ProjectId: projectId, RecordedAt: base, ServiceName: "checkout", ProfileType: "cpu", SampleCount: 2, TotalValue: 300},+ models.Profile{Id: uuid.New(), ProjectId: projectId, RecordedAt: base.Add(time.Minute), ServiceName: "checkout", ProfileType: "cpu", SampleCount: 1, TotalValue: 200},+ models.Profile{Id: uuid.New(), ProjectId: projectId, RecordedAt: base, ServiceName: "checkout", ProfileType: "inuse_space", SampleCount: 3, TotalValue: 9000},)- groups, total, err := ProfileRepository.FindGroupedByService(ctx, projectId, from, to, 1, 50, "total_value", "desc")+ groups, total, err := ProfileRepository.FindGroupedByService(ctx, projectId, from, to, 1, 50, "total_value", "desc", "")if err != nil {t.Fatalf("FindGroupedByService: %v", err)}@@ -77,11 +77,11 @@ func TestProfileRepository_FindGroupedByService(t *testing.T) {}byType[g.Type] = g}- cpu := byType[profiling.TypeCPUNanos]+ cpu := byType["cpu"]if cpu.ProfileCount != 2 || cpu.TotalValue != 500 || cpu.SampleCount != 3 {t.Errorf("cpu group = %+v, want ProfileCount=2 TotalValue=500 SampleCount=3", cpu)}- inuse := byType[profiling.TypeHeapInuseSpace]+ inuse := byType["inuse_space"]if inuse.ProfileCount != 1 || inuse.TotalValue != 9000 {t.Errorf("inuse group = %+v, want ProfileCount=1 TotalValue=9000", inuse)}@@ -105,7 +105,7 @@ func TestProfileRepository_GetFlameGraph_CounterMergesInstancesAndFiltersLabels(cpu := func(server string, hash uint64, value int64, env string) models.ProfileSample {return models.ProfileSample{ProjectId: projectId, ProfileId: uuid.New(), ServiceName: "checkout",- Type: profiling.TypeCPUNanos, Start: base, End: base.Add(30 * time.Second),+ Type: "cpu", Start: base, End: base.Add(30 * time.Second),StackHash: hash, Value: value, ServerName: server, Labels: map[string]string{"env": env},}}@@ -115,7 +115,7 @@ func TestProfileRepository_GetFlameGraph_CounterMergesInstancesAndFiltersLabels(cpu("pod-a", hashAC, 100, "dev"),)- all, err := ProfileRepository.GetFlameGraph(ctx, projectId, "checkout", profiling.TypeCPUNanos, from, to, nil)+ all, err := ProfileRepository.GetFlameGraph(ctx, projectId, "checkout", "cpu", from, to, nil, false, "", "")if err != nil {t.Fatalf("GetFlameGraph: %v", err)}@@ -127,7 +127,7 @@ func TestProfileRepository_GetFlameGraph_CounterMergesInstancesAndFiltersLabels(t.Errorf("a;c value = %d, want 100", got["a;c"])}- prod, err := ProfileRepository.GetFlameGraph(ctx, projectId, "checkout", profiling.TypeCPUNanos, from, to, map[string]string{"env": "prod"})+ prod, err := ProfileRepository.GetFlameGraph(ctx, projectId, "checkout", "cpu", from, to, map[string]string{"env": "prod"}, false, "", "")if err != nil {t.Fatalf("GetFlameGraph (filtered): %v", err)}@@ -157,7 +157,7 @@ func TestProfileRepository_GetFlameGraph_FiltersByDottedLabelKey(t *testing.T) {cpu := func(hash uint64, value int64, route string) models.ProfileSample {return models.ProfileSample{ProjectId: projectId, ProfileId: uuid.New(), ServiceName: "checkout",- Type: profiling.TypeCPUNanos, Start: base, End: base.Add(30 * time.Second),+ Type: "cpu", Start: base, End: base.Add(30 * time.Second),StackHash: hash, Value: value, Labels: map[string]string{"http.route": route},}}@@ -166,7 +166,7 @@ func TestProfileRepository_GetFlameGraph_FiltersByDottedLabelKey(t *testing.T) {cpu(hashAC, 100, "GET /cart"),)- rows, err := ProfileRepository.GetFlameGraph(ctx, projectId, "checkout", profiling.TypeCPUNanos, from, to, map[string]string{"http.route": "GET /checkout"})+ rows, err := ProfileRepository.GetFlameGraph(ctx, projectId, "checkout", "cpu", from, to, map[string]string{"http.route": "GET /checkout"}, false, "", "")if err != nil {t.Fatalf("GetFlameGraph (dotted filter): %v", err)}@@ -195,7 +195,7 @@ func TestProfileRepository_GetFlameGraph_GaugeUsesLatestPerServer(t *testing.T)inuse := func(server string, start time.Time, value int64) models.ProfileSample {return models.ProfileSample{ProjectId: projectId, ProfileId: uuid.New(), ServiceName: "checkout",- Type: profiling.TypeHeapInuseSpace, Start: start, End: start,+ Type: "inuse_space", Start: start, End: start,StackHash: hashX, Value: value, ServerName: server,}}@@ -207,7 +207,7 @@ func TestProfileRepository_GetFlameGraph_GaugeUsesLatestPerServer(t *testing.T)inuse("pod-b", t1, 50),)- rows, err := ProfileRepository.GetFlameGraph(ctx, projectId, "checkout", profiling.TypeHeapInuseSpace, from, to, nil)+ rows, err := ProfileRepository.GetFlameGraph(ctx, projectId, "checkout", "inuse_space", from, to, nil, true, "", "")if err != nil {t.Fatalf("GetFlameGraph (gauge): %v", err)}@@ -233,7 +233,7 @@ func TestProfileRepository_GetFlameGraph_GaugeDedupsTiedStartTimes(t *testing.T)inuse := func(server string, start time.Time, value int64) models.ProfileSample {return models.ProfileSample{ProjectId: projectId, ProfileId: uuid.New(), ServiceName: "checkout",- Type: profiling.TypeHeapInuseSpace, Start: start, End: start,+ Type: "inuse_space", Start: start, End: start,StackHash: hashX, Value: value, ServerName: server,}}@@ -243,7 +243,7 @@ func TestProfileRepository_GetFlameGraph_GaugeDedupsTiedStartTimes(t *testing.T)inuse("pod-b", base, 50),)- rows, err := ProfileRepository.GetFlameGraph(ctx, projectId, "checkout", profiling.TypeHeapInuseSpace, from, to, nil)+ rows, err := ProfileRepository.GetFlameGraph(ctx, projectId, "checkout", "inuse_space", from, to, nil, true, "", "")if err != nil {t.Fatalf("GetFlameGraph (gauge ties): %v", err)}@@ -266,7 +266,7 @@ func TestProfileRepository_GetSeries_CounterSumsPerBucket(t *testing.T) {sample := func(start time.Time, value int64) models.ProfileSample {return models.ProfileSample{ProjectId: projectId, ProfileId: uuid.New(), ServiceName: "checkout",- Type: profiling.TypeCPUNanos, Start: start, End: start, StackHash: hashX, Value: value,+ Type: "cpu", Start: start, End: start, StackHash: hashX, Value: value,}}mustInsertSamples(t, ctx,@@ -275,7 +275,7 @@ func TestProfileRepository_GetSeries_CounterSumsPerBucket(t *testing.T) {sample(h13.Add(10*time.Minute), 700),)- points, err := ProfileRepository.GetSeries(ctx, projectId, "checkout", profiling.TypeCPUNanos, from, to, 60)+ points, err := ProfileRepository.GetSeries(ctx, projectId, "checkout", "cpu", from, to, 60, false, nil, "", "", false)if err != nil {t.Fatalf("GetSeries: %v", err)}diff --git a/backend/app/repositories/profile_repository_test.go b/backend/app/repositories/profile_repository_test.goindex 4850a8eb..448bc3ca 100644--- a/backend/app/repositories/profile_repository_test.go+++ b/backend/app/repositories/profile_repository_test.go@@ -11,7 +11,6 @@ import ("github.com/google/uuid""github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/profiling")func TestProfileRepository_InsertAndReadBack(t *testing.T) {@@ -38,7 +37,7 @@ func TestProfileRepository_InsertAndReadBack(t *testing.T) {sample := models.ProfileSample{ProjectId: projectId, ProfileId: profileId, ServiceName: "checkout",- Type: profiling.TypeCPUNanos, Start: now, End: now.Add(30 * time.Second),+ Type: "cpu", Start: now, End: now.Add(30 * time.Second),StackHash: hash, Value: 300, ServerName: "pod-a", AppVersion: "1.2.3",}if err := ProfileRepository.InsertSamplesAsync(ctx, []models.ProfileSample{sample}); err != nil {@@ -47,7 +46,7 @@ func TestProfileRepository_InsertAndReadBack(t *testing.T) {prof := models.Profile{Id: profileId, ProjectId: projectId, RecordedAt: now, Duration: 30 * time.Second,- ServiceName: "checkout", ProfileType: profiling.TypeCPUNanos,+ ServiceName: "checkout", ProfileType: "cpu",SampleCount: 1, TotalValue: 300, ServerName: "pod-a", AppVersion: "1.2.3",}if err := ProfileRepository.InsertProfilesAsync(ctx, []models.Profile{prof}); err != nil {@@ -85,8 +84,8 @@ func TestProfileRepository_InsertAndReadBack(t *testing.T) {"SELECT type, value, stack_hash FROM profiling_samples LIMIT 1").Scan(&gotType, &gotValue, &gotSampleHash); err != nil {t.Fatalf("read sample: %v", err)}- if gotType != profiling.TypeCPUNanos || gotValue != 300 || uint64(gotSampleHash) != hash {- t.Errorf("sample = (%s,%d,%d), want (%s,300,%d)", gotType, gotValue, uint64(gotSampleHash), profiling.TypeCPUNanos, hash)+ if gotType != "cpu" || gotValue != 300 || uint64(gotSampleHash) != hash {+ t.Errorf("sample = (%s,%d,%d), want (%s,300,%d)", gotType, gotValue, uint64(gotSampleHash), "cpu", hash)}var gotTotal int64@@ -95,7 +94,7 @@ func TestProfileRepository_InsertAndReadBack(t *testing.T) {"SELECT profile_type, total_value FROM profiles WHERE id = ?", profileId.String()).Scan(&gotProfileType, &gotTotal); err != nil {t.Fatalf("read profile: %v", err)}- if gotProfileType != profiling.TypeCPUNanos || gotTotal != 300 {- t.Errorf("profile = (%s,%d), want (%s,300)", gotProfileType, gotTotal, profiling.TypeCPUNanos)+ if gotProfileType != "cpu" || gotTotal != 300 {+ t.Errorf("profile = (%s,%d), want (%s,300)", gotProfileType, gotTotal, "cpu")}}diff --git a/backend/app/repositories/testhelper_sqlite_test.go b/backend/app/repositories/testhelper_sqlite_test.goindex 751e5044..832a4f3f 100644--- a/backend/app/repositories/testhelper_sqlite_test.go+++ b/backend/app/repositories/testhelper_sqlite_test.go@@ -218,6 +218,8 @@ CREATE TABLE IF NOT EXISTS profiling_samples (profile_id TEXT NOT NULL,service_name TEXT NOT NULL DEFAULT '',type TEXT NOT NULL DEFAULT '',+ unit TEXT NOT NULL DEFAULT '',+ is_gauge INTEGER NOT NULL DEFAULT 0,start_time DATETIME NOT NULL,end_time DATETIME NOT NULL,stack_hash INTEGER NOT NULL,@@ -237,6 +239,8 @@ CREATE TABLE IF NOT EXISTS profiles (duration INTEGER NOT NULL DEFAULT 0,service_name TEXT NOT NULL DEFAULT '',profile_type TEXT NOT NULL DEFAULT '',+ unit TEXT NOT NULL DEFAULT '',+ is_gauge INTEGER NOT NULL DEFAULT 0,sample_count INTEGER NOT NULL DEFAULT 0,total_value INTEGER NOT NULL DEFAULT 0,server_name TEXT NOT NULL DEFAULT '',diff --git a/backend/app/services/profile_flamegraph.go b/backend/app/services/profile_flamegraph.goindex fe1e5d1e..fb1a0542 100644--- a/backend/app/services/profile_flamegraph.go+++ b/backend/app/services/profile_flamegraph.go@@ -6,6 +6,11 @@ import ("github.com/tracewayapp/traceway/backend/app/models")+const (+ maxFlameDepth = 256+ maxFlameNodes = 60000+)+type FlameNode struct {Name string `json:"name"`Value int64 `json:"value"`@@ -16,11 +21,17 @@ type FlameNode struct {func FoldFlameGraph(stacks []models.ProfileStackValue) *FlameNode {root := &FlameNode{Name: "root"}childIndex := map[*FlameNode]map[string]*FlameNode{}+ nodeCount := 0for _, s := range stacks {root.Value += s.Valuenode := root- for i, frame := range s.Stack {+ depth := len(s.Stack)+ if depth > maxFlameDepth {+ depth = maxFlameDepth+ }+ for i := 0; i < depth; i++ {+ frame := s.Stack[i]children, ok := childIndex[node]if !ok {children = map[string]*FlameNode{}@@ -28,12 +39,16 @@ func FoldFlameGraph(stacks []models.ProfileStackValue) *FlameNode {}child, ok := children[frame]if !ok {+ if nodeCount >= maxFlameNodes {+ break+ }child = &FlameNode{Name: frame}children[frame] = childnode.Children = append(node.Children, child)+ nodeCount++}child.Value += s.Value- if i == len(s.Stack)-1 {+ if i == depth-1 {child.Self += s.Value}node = childdiff --git a/backend/app/services/profile_pprof_export.go b/backend/app/services/profile_pprof_export.gonew file mode 100644index 00000000..9afd5833--- /dev/null+++ b/backend/app/services/profile_pprof_export.go@@ -0,0 +1,64 @@+package services++import (+ "bytes"++ "github.com/google/pprof/profile"+ "github.com/tracewayapp/traceway/backend/app/models"+)++func BuildPprof(name, unit string, stacks []models.ProfileStackValue) ([]byte, error) {+ if name == "" {+ name = "samples"+ }+ if unit == "" {+ unit = "count"+ }++ p := &profile.Profile{+ SampleType: []*profile.ValueType{{Type: name, Unit: unit}},+ }++ funcs := map[string]*profile.Function{}+ locs := map[string]*profile.Location{}+ var nextID uint64 = 1++ locFor := func(frame string) *profile.Location {+ if l, ok := locs[frame]; ok {+ return l+ }+ f, ok := funcs[frame]+ if !ok {+ f = &profile.Function{ID: nextID, Name: frame, SystemName: frame}+ nextID+++ funcs[frame] = f+ p.Function = append(p.Function, f)+ }+ l := &profile.Location{ID: nextID, Line: []profile.Line{{Function: f}}}+ nextID+++ locs[frame] = l+ p.Location = append(p.Location, l)+ return l+ }++ for _, s := range stacks {+ if len(s.Stack) == 0 {+ continue+ }+ leafFirst := make([]*profile.Location, 0, len(s.Stack))+ for i := len(s.Stack) - 1; i >= 0; i-- {+ leafFirst = append(leafFirst, locFor(s.Stack[i]))+ }+ p.Sample = append(p.Sample, &profile.Sample{Location: leafFirst, Value: []int64{s.Value}})+ }++ if err := p.CheckValid(); err != nil {+ return nil, err+ }++ var buf bytes.Buffer+ if err := p.Write(&buf); err != nil {+ return nil, err+ }+ return buf.Bytes(), nil+}diff --git a/backend/app/services/profile_pprof_export_test.go b/backend/app/services/profile_pprof_export_test.gonew file mode 100644index 00000000..8eb6af70--- /dev/null+++ b/backend/app/services/profile_pprof_export_test.go@@ -0,0 +1,73 @@+package services++import (+ "bytes"+ "testing"++ "github.com/google/pprof/profile"+ "github.com/tracewayapp/traceway/backend/app/models"+)++func TestBuildPprof_RoundTrips(t *testing.T) {+ stacks := []models.ProfileStackValue{+ {Stack: []string{"main.main", "net/http.serve", "checkout.Handle", "db.Query"}, Value: 300},+ {Stack: []string{"main.main", "net/http.serve", "cart.Add", "cache.Get"}, Value: 100},+ }++ raw, err := BuildPprof("cpu", "nanoseconds", stacks)+ if err != nil {+ t.Fatalf("BuildPprof: %v", err)+ }++ p, err := profile.Parse(bytes.NewReader(raw))+ if err != nil {+ t.Fatalf("re-parse exported pprof: %v", err)+ }++ if len(p.SampleType) != 1 || p.SampleType[0].Type != "cpu" || p.SampleType[0].Unit != "nanoseconds" {+ t.Fatalf("sample type = %+v, want cpu/nanoseconds", p.SampleType)+ }+ if len(p.Sample) != 2 {+ t.Fatalf("samples = %d, want 2", len(p.Sample))+ }++ var total int64+ for _, s := range p.Sample {+ total += s.Value[0]+ leaf := s.Location[0].Line[0].Function.Name+ if leaf != "db.Query" && leaf != "cache.Get" {+ t.Errorf("leaf (first location) = %q, want a leaf frame", leaf)+ }+ }+ if total != 400 {+ t.Errorf("total value = %d, want 400", total)+ }+}++func TestBuildPprof_PreservesArbitraryTypeAndUnit(t *testing.T) {+ raw, err := BuildPprof("lock", "nanoseconds", []models.ProfileStackValue{{Stack: []string{"a"}, Value: 1}})+ if err != nil {+ t.Fatalf("BuildPprof: %v", err)+ }+ p, err := profile.Parse(bytes.NewReader(raw))+ if err != nil {+ t.Fatalf("re-parse: %v", err)+ }+ if p.SampleType[0].Type != "lock" || p.SampleType[0].Unit != "nanoseconds" {+ t.Errorf("sample type = %+v, want lock/nanoseconds (arbitrary type carried through)", p.SampleType[0])+ }+}++func TestBuildPprof_EmptyTypeFallsBack(t *testing.T) {+ raw, err := BuildPprof("", "", []models.ProfileStackValue{{Stack: []string{"a"}, Value: 1}})+ if err != nil {+ t.Fatalf("BuildPprof: %v", err)+ }+ p, err := profile.Parse(bytes.NewReader(raw))+ if err != nil {+ t.Fatalf("re-parse: %v", err)+ }+ if p.SampleType[0].Type != "samples" || p.SampleType[0].Unit != "count" {+ t.Errorf("fallback sample type = %+v, want samples/count", p.SampleType[0])+ }+}diff --git a/backend/app/services/profile_topfunctions.go b/backend/app/services/profile_topfunctions.gonew file mode 100644index 00000000..84c3311b--- /dev/null+++ b/backend/app/services/profile_topfunctions.go@@ -0,0 +1,69 @@+package services++import (+ "sort"++ "github.com/tracewayapp/traceway/backend/app/models"+)++type FunctionStat struct {+ Name string `json:"name"`+ Flat int64 `json:"flat"`+ Cum int64 `json:"cum"`+ FlatPct float64 `json:"flatPct"`+ CumPct float64 `json:"cumPct"`+}++func TopFunctions(stacks []models.ProfileStackValue, limit int) []FunctionStat {+ flat := map[string]int64{}+ cum := map[string]int64{}+ var total int64++ for _, s := range stacks {+ total += s.Value+ if len(s.Stack) > 0 {+ flat[s.Stack[len(s.Stack)-1]] += s.Value+ }+ seen := map[string]struct{}{}+ for _, frame := range s.Stack {+ if _, ok := seen[frame]; ok {+ continue+ }+ seen[frame] = struct{}{}+ cum[frame] += s.Value+ }+ }++ names := map[string]struct{}{}+ for n := range flat {+ names[n] = struct{}{}+ }+ for n := range cum {+ names[n] = struct{}{}+ }++ out := make([]FunctionStat, 0, len(names))+ for n := range names {+ stat := FunctionStat{Name: n, Flat: flat[n], Cum: cum[n]}+ if total > 0 {+ stat.FlatPct = float64(stat.Flat) / float64(total) * 100+ stat.CumPct = float64(stat.Cum) / float64(total) * 100+ }+ out = append(out, stat)+ }++ sort.SliceStable(out, func(i, j int) bool {+ if out[i].Flat != out[j].Flat {+ return out[i].Flat > out[j].Flat+ }+ if out[i].Cum != out[j].Cum {+ return out[i].Cum > out[j].Cum+ }+ return out[i].Name < out[j].Name+ })++ if limit > 0 && len(out) > limit {+ out = out[:limit]+ }+ return out+}diff --git a/backend/app/services/profile_topfunctions_test.go b/backend/app/services/profile_topfunctions_test.gonew file mode 100644index 00000000..021c24d5--- /dev/null+++ b/backend/app/services/profile_topfunctions_test.go@@ -0,0 +1,84 @@+package services++import (+ "testing"++ "github.com/tracewayapp/traceway/backend/app/models"+)++func statByName(stats []FunctionStat, name string) (FunctionStat, bool) {+ for _, s := range stats {+ if s.Name == name {+ return s, true+ }+ }+ return FunctionStat{}, false+}++func TestTopFunctions_FlatAndCum(t *testing.T) {+ stacks := []models.ProfileStackValue{+ {Stack: []string{"main", "serve", "checkout", "query"}, Value: 300},+ {Stack: []string{"main", "serve", "checkout"}, Value: 50},+ {Stack: []string{"main", "serve", "cart", "get"}, Value: 100},+ }++ stats := TopFunctions(stacks, 0)++ main, ok := statByName(stats, "main")+ if !ok {+ t.Fatal("main missing")+ }+ if main.Flat != 0 {+ t.Errorf("main flat = %d, want 0 (never a leaf)", main.Flat)+ }+ if main.Cum != 450 {+ t.Errorf("main cum = %d, want 450 (every sample passes through main)", main.Cum)+ }++ query, _ := statByName(stats, "query")+ if query.Flat != 300 || query.Cum != 300 {+ t.Errorf("query = flat %d cum %d, want 300/300", query.Flat, query.Cum)+ }++ checkout, _ := statByName(stats, "checkout")+ if checkout.Flat != 50 {+ t.Errorf("checkout flat = %d, want 50 (leaf only on the 50 sample)", checkout.Flat)+ }+ if checkout.Cum != 350 {+ t.Errorf("checkout cum = %d, want 350 (300 + 50)", checkout.Cum)+ }++ if want := float64(450) / float64(450) * 100; main.CumPct != want {+ t.Errorf("main cumPct = %f, want %f", main.CumPct, want)+ }+}++func TestTopFunctions_RecursionDedupesWithinStack(t *testing.T) {+ stacks := []models.ProfileStackValue{+ {Stack: []string{"main", "recurse", "recurse", "recurse", "leaf"}, Value: 100},+ }+ stats := TopFunctions(stacks, 0)++ recurse, _ := statByName(stats, "recurse")+ if recurse.Cum != 100 {+ t.Errorf("recurse cum = %d, want 100 (counted once per stack despite 3 frames)", recurse.Cum)+ }+ if recurse.Flat != 0 {+ t.Errorf("recurse flat = %d, want 0 (leaf is 'leaf')", recurse.Flat)+ }+}++func TestTopFunctions_SortedByFlatThenLimited(t *testing.T) {+ stacks := []models.ProfileStackValue{+ {Stack: []string{"a"}, Value: 10},+ {Stack: []string{"b"}, Value: 30},+ {Stack: []string{"c"}, Value: 20},+ }+ stats := TopFunctions(stacks, 2)+ if len(stats) != 2 {+ t.Fatalf("got %d stats, want 2 (limited)", len(stats))+ }+ if stats[0].Name != "b" || stats[1].Name != "c" {+ t.Errorf("order = [%s %s], want [b c] (flat desc)", stats[0].Name, stats[1].Name)+ }+}diff --git a/frontend/src/d3-flame-graph.d.ts b/frontend/src/d3-flame-graph.d.tsindex bfa7b072..1732f818 100644--- a/frontend/src/d3-flame-graph.d.ts+++ b/frontend/src/d3-flame-graph.d.ts@@ -3,9 +3,16 @@ declare module 'd3-flame-graph' {name: string;value: number;self?: number;+ delta?: number;children?: FlameGraphNode[];}+ export interface FlameGraphHierarchyNode {+ data: FlameGraphNode;+ value: number;+ parent: FlameGraphHierarchyNode | null;+ }+export interface FlameGraph {(selection: unknown): void;width(value: number): FlameGraph;@@ -16,12 +23,15 @@ declare module 'd3-flame-graph' {inverted(value: boolean): FlameGraph;sort(value: boolean): FlameGraph;selfValue(value: boolean): FlameGraph;- setColorMapper(fn: (node: unknown, originalColor: string) => string): FlameGraph;- label(fn: (node: { data: FlameGraphNode }) => string): FlameGraph;- onClick(fn: (node: unknown) => void): FlameGraph;+ setColorMapper(+ fn: (node: FlameGraphHierarchyNode, originalColor: string) => string+ ): FlameGraph;+ label(fn: (node: FlameGraphHierarchyNode) => string): FlameGraph;+ onClick(fn: (node: FlameGraphHierarchyNode) => void): FlameGraph;resetZoom(): void;search(term: string): void;clear(): void;+ update(root?: FlameGraphNode): void;destroy(): void;}diff --git a/frontend/src/lib/components/profiles/flame-graph.svelte b/frontend/src/lib/components/profiles/flame-graph.svelteindex bb8e2357..c17cc8c8 100644--- a/frontend/src/lib/components/profiles/flame-graph.svelte+++ b/frontend/src/lib/components/profiles/flame-graph.svelte@@ -1,31 +1,87 @@<script module lang="ts">- import { formatProfileValue } from '$lib/utils/profile-format';+ import { formatValue } from '$lib/utils/profile-format';+ import type { FlameGraphNode } from 'd3-flame-graph';++ function trimPct(pct: number): string {+ return Number(pct.toFixed(1)).toString();+ }export function flameTooltipLabel(name: string,value: number,+ self: number,+ parentValue: number,total: number,- type: string+ unit: string): string {- const pct = total > 0 ? (value / total) * 100 : 0;- const pctStr = Number(pct.toFixed(1)).toString();- return `${name} — ${formatProfileValue(type, value)} (${pctStr}%)`;+ const pctTotal = total > 0 ? (value / total) * 100 : 0;+ const parts = [name, `${formatValue(unit, value)} (${trimPct(pctTotal)}% of total)`];+ if (parentValue > 0 && parentValue !== value) {+ parts.push(`${trimPct((value / parentValue) * 100)}% of parent`);+ }+ if (self > 0 && self !== value) {+ parts.push(`self ${formatValue(unit, self)}`);+ }+ return parts.join(' · ');+ }++ export function diffColor(delta: number): string {+ const mag = Math.min(1, Math.abs(delta));+ if (delta > 0.001) return `hsl(8, ${Math.round(45 + mag * 45)}%, ${Math.round(68 - mag * 22)}%)`;+ if (delta < -0.001)+ return `hsl(140, ${Math.round(40 + mag * 45)}%, ${Math.round(66 - mag * 20)}%)`;+ return 'hsl(220, 6%, 78%)';+ }++ export function flameDepth(node: FlameGraphNode): number {+ if (!node.children || node.children.length === 0) return 0;+ let max = 0;+ for (const child of node.children) {+ const d = flameDepth(child);+ if (d > max) max = d;+ }+ return max + 1;}</script><script lang="ts">- import flamegraph, { type FlameGraphNode } from 'd3-flame-graph';+ import flamegraph, { type FlameGraph } from 'd3-flame-graph';import { select } from 'd3-selection';+ import { untrack } from 'svelte';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { RotateCcw, FlipVertical2 } from '@lucide/svelte';interface Props {data: FlameGraphNode | null;- type: string;+ unit: string;+ diff?: boolean;+ controls?: boolean;+ searchTerm?: string;+ inverted?: boolean;+ onFrameSelect?: (name: string) => void;}- let { data, type }: Props = $props();+ let {+ data,+ unit,+ diff = false,+ controls = true,+ searchTerm = $bindable(''),+ inverted: invertedProp = false,+ onFrameSelect+ }: Props = $props();++ const CELL = 20;let container = $state<HTMLDivElement>();let width = $state(0);+ let chart: FlameGraph | null = null;++ let inverted = $state(invertedProp);++ const contentHeight = $derived(data ? (flameDepth(data) + 1) * CELL : 0);+ const svgShift = $derived(inverted ? 0 : -2 * CELL);$effect(() => {const el = container;@@ -42,28 +98,74 @@if (!el || !data) return;const total = data.value || 0;- const currentType = type;- const chart = flamegraph()- .width(width || el.clientWidth || 960)- .cellHeight(20)+ const currentUnit = unit;++ const instance = flamegraph()+ .width(el.clientWidth || 960)+ .cellHeight(CELL).minFrameSize(1).transitionDuration(200).sort(true).selfValue(false)- .label((d) => flameTooltipLabel(d.data.name, d.data.value, total, currentType));+ .inverted(inverted)+ .label((d) =>+ flameTooltipLabel(+ d.data.name,+ d.data.value,+ d.data.self ?? 0,+ d.parent?.data.value ?? 0,+ total,+ currentUnit+ )+ );++ if (diff) {+ instance.setColorMapper((node) => diffColor(node.data.delta ?? 0));+ }++ if (onFrameSelect) {+ instance.onClick((node) => onFrameSelect(node.data.name));+ }- select(el).datum(data).call(chart);+ select(el).datum(data).call(instance);+ chart = instance;++ const active = untrack(() => searchTerm).trim();+ if (active) instance.search(active);return () => {try {- chart.destroy();+ instance.destroy();} catch {- // destroy() can throw if the chart never finished mounting; the- // unconditional clear below is the real teardown either way.+ select(el).selectAll('*').remove();}select(el).selectAll('*').remove();+ chart = null;};});++ $effect(() => {+ const w = width;+ if (!chart || !w) return;+ try {+ chart.width(w);+ chart.update();+ } catch {+ /* resize is best-effort */+ }+ });++ $effect(() => {+ const term = searchTerm.trim();+ void data;+ if (!chart) return;+ if (term) chart.search(term);+ else chart.clear();+ });++ function resetZoom() {+ chart?.resetZoom();+ }</script>{#if !data}@@ -73,10 +175,54 @@No flame graph data for this range.</div>{:else}- <div bind:this={container} class="flame-graph w-full"></div>+ <div class="mb-3 flex flex-wrap items-center gap-2">+ {#if controls}+ <Input+ type="text"+ placeholder="Search frames…"+ bind:value={searchTerm}+ data-testid="flame-search"+ class="h-8 w-56"+ />+ {/if}+ <div class="flex-1"></div>+ <Button+ variant="outline"+ size="sm"+ onclick={resetZoom}+ data-testid="flame-reset"+ title="Reset zoom"+ >+ <RotateCcw class="h-4 w-4" />+ Reset+ </Button>+ {#if controls}+ <Button+ variant={inverted ? 'secondary' : 'outline'}+ size="sm"+ aria-pressed={inverted}+ onclick={() => (inverted = !inverted)}+ data-testid="flame-icicle"+ title="Toggle icicle (top-down) view"+ >+ <FlipVertical2 class="h-4 w-4" />+ Icicle+ </Button>+ {/if}+ </div>+ <div+ bind:this={container}+ class="flame-graph w-full overflow-hidden"+ style="height: {contentHeight}px; --flame-svg-shift: {svgShift}px"+ ></div>{/if}<style>+ :global(.flame-graph svg) {+ display: block;+ margin-top: var(--flame-svg-shift, 0);+ }+:global(.flame-graph .d3-flame-graph rect) {stroke: var(--background);stroke-width: 0.5;@@ -99,10 +245,14 @@margin-right: 4px;line-height: 1.5;font-weight: 400;- color: #fff;+ color: #18181b;text-align: left;}+ :global(.dark .flame-graph .d3-flame-graph-label) {+ color: #fff;+ }+:global(.flame-graph .d3-flame-graph .fade) {opacity: 0.5 !important;}diff --git a/frontend/src/lib/components/profiles/flame-graph.test.ts b/frontend/src/lib/components/profiles/flame-graph.test.tsindex 5b3fd95e..311e20e0 100644--- a/frontend/src/lib/components/profiles/flame-graph.test.ts+++ b/frontend/src/lib/components/profiles/flame-graph.test.ts@@ -21,7 +21,8 @@ vi.mock('d3-selection', () => {});import FlameGraph, { flameTooltipLabel } from './flame-graph.svelte';-import { CPU_NANOS } from '$lib/utils/profile-format';++const NS = 'nanoseconds';const tree = {name: 'root',@@ -31,14 +32,28 @@ const tree = {};describe('flameTooltipLabel', () => {- it('formats name, value and percentage of total', () => {- expect(flameTooltipLabel('main.work', 1_500_000, 4_000_000, CPU_NANOS)).toBe(- 'main.work — 1.5 ms (37.5%)'+ it('formats name, value, % of total and % of parent', () => {+ expect(flameTooltipLabel('main.work', 1_500_000, 0, 3_000_000, 4_000_000, NS)).toBe(+ 'main.work · 1.5 ms (37.5% of total) · 50% of parent'+ );+ });++ it('appends self time when a frame has non-leaf self', () => {+ expect(flameTooltipLabel('main.serve', 100, 40, 200, 200, NS)).toBe(+ 'main.serve · 100 ns (50% of total) · 50% of parent · self 40 ns');});- it('renders 0% instead of NaN when the total is zero', () => {- expect(flameTooltipLabel('main.work', 10, 0, CPU_NANOS)).toBe('main.work — 10 ns (0%)');+ it('omits the self line for a leaf where self equals value', () => {+ expect(flameTooltipLabel('main.leaf', 60, 60, 100, 100, NS)).toBe(+ 'main.leaf · 60 ns (60% of total) · 60% of parent'+ );+ });++ it('renders 0% and no parent/self when the total and parent are zero', () => {+ expect(flameTooltipLabel('main.work', 10, 0, 0, 0, NS)).toBe(+ 'main.work · 10 ns (0% of total)'+ );});});@@ -49,22 +64,22 @@ describe('FlameGraph component', () => {});it('shows an empty state and does not render a chart when data is null', () => {- const { getByText } = render(FlameGraph, { props: { data: null, type: CPU_NANOS } });+ const { getByText } = render(FlameGraph, { props: { data: null, unit: NS } });expect(getByText(/no flame graph data/i)).toBeTruthy();expect(flamegraphSpy).not.toHaveBeenCalled();});it('renders the d3 flame graph with the provided tree', () => {- render(FlameGraph, { props: { data: tree, type: CPU_NANOS } });+ render(FlameGraph, { props: { data: tree, unit: NS } });expect(flamegraphSpy).toHaveBeenCalled();expect(datumSpy).toHaveBeenCalledWith(tree);});it('re-renders when the data prop changes', async () => {- const { rerender } = render(FlameGraph, { props: { data: tree, type: CPU_NANOS } });+ const { rerender } = render(FlameGraph, { props: { data: tree, unit: NS } });datumSpy.mockClear();const next = { name: 'root', value: 50, self: 0, children: [] };- await rerender({ data: next, type: CPU_NANOS });+ await rerender({ data: next, unit: NS });expect(datumSpy).toHaveBeenCalledWith(next);});});diff --git a/frontend/src/lib/components/profiles/profile-series-chart.svelte b/frontend/src/lib/components/profiles/profile-series-chart.sveltenew file mode 100644index 00000000..80156c33--- /dev/null+++ b/frontend/src/lib/components/profiles/profile-series-chart.svelte@@ -0,0 +1,245 @@+<script module lang="ts">+ export type SeriesPoint = { timestamp: string; value: number };+ export type SeriesGroup = { key: string; points: SeriesPoint[] };++ const PALETTE = [+ 'hsl(217, 91%, 60%)',+ 'hsl(160, 60%, 45%)',+ 'hsl(35, 92%, 55%)',+ 'hsl(280, 65%, 60%)',+ 'hsl(0, 72%, 58%)',+ 'hsl(190, 80%, 45%)',+ 'hsl(50, 90%, 50%)',+ 'hsl(330, 70%, 60%)'+ ];++ export function seriesColor(i: number): string {+ return PALETTE[i % PALETTE.length];+ }++ function clamp(x: number, lo: number, hi: number): number {+ return Math.max(lo, Math.min(hi, x));+ }+</script>++<script lang="ts">+ import { formatValue, formatRate } from '$lib/utils/profile-format';+ import { getTimezone } from '$lib/state/timezone.svelte';+ import { DateTime } from 'luxon';++ interface Props {+ series?: SeriesPoint[];+ groups?: SeriesGroup[];+ unit: string;+ isRate?: boolean;+ height?: number;+ onSelectRange?: (fromIso: string, toIso: string) => void;+ }++ let { series = [], groups = [], unit, isRate = false, height = 140, onSelectRange }: Props = $props();++ const timezone = $derived(getTimezone());++ let container = $state<HTMLDivElement>();+ let width = $state(0);++ $effect(() => {+ const el = container;+ if (!el || typeof ResizeObserver === 'undefined') return;+ const observer = new ResizeObserver((entries) => {+ width = entries[0].contentRect.width;+ });+ observer.observe(el);+ width = el.clientWidth;+ return () => observer.disconnect();+ });++ const padL = 6;+ const padR = 6;+ const padT = 10;+ const padB = 20;++ const lines = $derived.by(() => {+ if (groups.length) return groups.map((g, i) => ({ key: g.key, points: g.points, color: seriesColor(i) }));+ if (series.length) return [{ key: '', points: series, color: 'var(--primary)' }];+ return [] as { key: string; points: SeriesPoint[]; color: string }[];+ });++ const allPoints = $derived(lines.flatMap((l) => l.points));+ const times = $derived(allPoints.map((p) => new Date(p.timestamp).getTime()));+ const tMin = $derived(times.length ? Math.min(...times) : 0);+ const tMax = $derived(times.length ? Math.max(...times) : 0);+ const vMax = $derived(Math.max(1, ...allPoints.map((p) => p.value)));++ const plotW = $derived(Math.max(0, width - padL - padR));+ const plotH = $derived(Math.max(0, height - padT - padB));++ function xOf(ts: number): number {+ if (tMax === tMin) return padL;+ return padL + ((ts - tMin) / (tMax - tMin)) * plotW;+ }+ function yOf(v: number): number {+ return padT + plotH - (v / vMax) * plotH;+ }+ function pathFor(points: SeriesPoint[]): string {+ return points+ .map(+ (p, i) =>+ `${i === 0 ? 'M' : 'L'} ${xOf(new Date(p.timestamp).getTime()).toFixed(1)} ${yOf(p.value).toFixed(1)}`+ )+ .join(' ');+ }++ function fmt(v: number): string {+ return isRate ? formatRate(unit, v) : formatValue(unit, v);+ }+ function fmtTime(ts: number): string {+ const span = tMax - tMin;+ const dt = DateTime.fromMillis(ts).setZone(timezone);+ return span > 36 * 60 * 60 * 1000 ? dt.toFormat('MMM d HH:mm') : dt.toFormat('HH:mm');+ }++ let dragStart = $state<number | null>(null);+ let dragEnd = $state<number | null>(null);+ let hoverX = $state<number | null>(null);++ function localX(e: PointerEvent): number {+ const rect = container!.getBoundingClientRect();+ return e.clientX - rect.left;+ }++ function onPointerDown(e: PointerEvent) {+ if (!container || !onSelectRange) return;+ dragStart = localX(e);+ dragEnd = dragStart;+ (e.currentTarget as Element).setPointerCapture?.(e.pointerId);+ }+ function onPointerMove(e: PointerEvent) {+ if (!container) return;+ hoverX = localX(e);+ if (dragStart !== null) dragEnd = hoverX;+ }+ function onPointerUp() {+ const start = dragStart;+ const end = dragEnd;+ dragStart = null;+ dragEnd = null;+ if (start === null || end === null || !onSelectRange || tMax === tMin) return;+ const x0 = Math.min(start, end);+ const x1 = Math.max(start, end);+ if (x1 - x0 < 5) return;+ const toTs = (x: number) =>+ tMin + ((clamp(x, padL, padL + plotW) - padL) / plotW) * (tMax - tMin);+ onSelectRange(new Date(toTs(x0)).toISOString(), new Date(toTs(x1)).toISOString());+ }+ function onPointerLeave() {+ hoverX = null;+ }++ const hoverIdx = $derived.by(() => {+ if (hoverX === null || !lines.length || tMax === tMin) return -1;+ const ts = tMin + ((clamp(hoverX, padL, padL + plotW) - padL) / plotW) * (tMax - tMin);+ const base = lines[0].points;+ let best = 0;+ let bestD = Infinity;+ for (let i = 0; i < base.length; i++) {+ const d = Math.abs(new Date(base[i].timestamp).getTime() - ts);+ if (d < bestD) {+ bestD = d;+ best = i;+ }+ }+ return best;+ });+</script>++<div class="w-full">+ <div+ bind:this={container}+ class="relative w-full select-none"+ style="height: {height}px; touch-action: none;"+ role="presentation"+ onpointerdown={onPointerDown}+ onpointermove={onPointerMove}+ onpointerup={onPointerUp}+ onpointerleave={onPointerLeave}+ >+ {#if allPoints.length < 2}+ <div class="flex h-full items-center justify-center text-sm text-muted-foreground">+ Not enough data in this range.+ </div>+ {:else}+ <svg {width} {height} class="block {onSelectRange ? 'cursor-crosshair' : ''}">+ <line+ x1={padL}+ y1={padT}+ x2={padL}+ y2={padT + plotH}+ class="stroke-border"+ stroke-width="1"+ />+ <line+ x1={padL}+ y1={padT + plotH}+ x2={padL + plotW}+ y2={padT + plotH}+ class="stroke-border"+ stroke-width="1"+ />++ {#each lines as line (line.key)}+ <path+ d={pathFor(line.points)}+ fill="none"+ stroke={line.color}+ stroke-width="1.5"+ stroke-linejoin="round"+ />+ {/each}++ {#if hoverIdx >= 0 && lines[0]?.points[hoverIdx]}+ {@const hx = xOf(new Date(lines[0].points[hoverIdx].timestamp).getTime())}+ <line x1={hx} y1={padT} x2={hx} y2={padT + plotH} class="stroke-muted-foreground/40" stroke-width="1" />+ {/if}++ {#if dragStart !== null && dragEnd !== null}+ {@const a = Math.min(dragStart, dragEnd)}+ {@const b = Math.max(dragStart, dragEnd)}+ <rect x={a} y={padT} width={Math.max(0, b - a)} height={plotH} class="fill-primary/15 stroke-primary/50" stroke-width="1" />+ {/if}++ <text x={padL} y={padT - 2} class="fill-muted-foreground" style="font-size: 10px;">{fmt(vMax)}</text>+ <text x={padL} y={height - 6} class="fill-muted-foreground" style="font-size: 10px;">{fmtTime(tMin)}</text>+ <text x={padL + plotW} y={height - 6} text-anchor="end" class="fill-muted-foreground" style="font-size: 10px;">{fmtTime(tMax)}</text>+ </svg>++ {#if hoverIdx >= 0 && lines[0]?.points[hoverIdx]}+ <div class="pointer-events-none absolute right-1 top-1 rounded border bg-popover px-2 py-1 text-xs text-popover-foreground shadow-sm">+ <div class="text-muted-foreground">{fmtTime(new Date(lines[0].points[hoverIdx].timestamp).getTime())}</div>+ {#each lines as line (line.key)}+ <div class="flex items-center gap-1.5 tabular-nums">+ <span class="inline-block h-2 w-2 rounded-sm" style="background: {line.color}"></span>+ {#if line.key}<span class="text-muted-foreground">{line.key}</span>{/if}+ <span>{fmt(line.points[hoverIdx]?.value ?? 0)}</span>+ </div>+ {/each}+ </div>+ {/if}+ {/if}+ </div>++ {#if groups.length}+ <div class="mt-1 flex flex-wrap gap-x-3 gap-y-1">+ {#each lines as line (line.key)}+ <span class="inline-flex items-center gap-1.5 text-xs text-muted-foreground">+ <span class="inline-block h-2 w-2 rounded-sm" style="background: {line.color}"></span>+ <span class="max-w-[12rem] truncate">{line.key || '(empty)'}</span>+ </span>+ {/each}+ </div>+ {/if}++ {#if onSelectRange && allPoints.length >= 2}+ <div class="mt-1 text-center text-[11px] text-muted-foreground">Drag to zoom into a time range</div>+ {/if}+</div>diff --git a/frontend/src/lib/components/profiles/top-functions-table.svelte b/frontend/src/lib/components/profiles/top-functions-table.sveltenew file mode 100644index 00000000..b1997f97--- /dev/null+++ b/frontend/src/lib/components/profiles/top-functions-table.svelte@@ -0,0 +1,145 @@+<script module lang="ts">+ export interface FunctionStat {+ name: string;+ flat: number;+ cum: number;+ flatPct: number;+ cumPct: number;+ }+</script>++<script lang="ts">+ import * as Table from '$lib/components/ui/table';+ import TracewayTableHeader from '$lib/components/ui/traceway-table-header/traceway-table-header.svelte';+ import { Button } from '$lib/components/ui/button';+ import { formatValue } from '$lib/utils/profile-format';++ interface Props {+ rows: FunctionStat[];+ unit: string;+ onSelect?: (name: string) => void;+ baselineRows?: FunctionStat[];+ }++ let { rows, unit, onSelect, baselineRows }: Props = $props();++ let sortField = $state<'flat' | 'cum'>('flat');+ let sortDirection = $state<'asc' | 'desc'>('desc');+ let expanded = $state(false);++ const COLLAPSED = 15;++ const baseFlat = $derived.by(() => {+ const m = new Map<string, number>();+ for (const r of baselineRows ?? []) m.set(r.name, r.flat);+ return m;+ });++ function onSort(field: string) {+ const next = field as 'flat' | 'cum';+ if (sortField === next) {+ sortDirection = sortDirection === 'desc' ? 'asc' : 'desc';+ } else {+ sortField = next;+ sortDirection = 'desc';+ }+ }++ const sorted = $derived.by(() => {+ const copy = [...rows];+ copy.sort((a, b) =>+ sortDirection === 'desc' ? b[sortField] - a[sortField] : a[sortField] - b[sortField]+ );+ return copy;+ });++ const visible = $derived(expanded ? sorted : sorted.slice(0, COLLAPSED));++ function pct(value: number): string {+ return `${Number(value.toFixed(1))}%`;+ }++ function deltaLabel(row: FunctionStat): { text: string; cls: string } {+ const base = baseFlat.get(row.name) ?? 0;+ const d = row.flat - base;+ if (d === 0) return { text: '—', cls: 'text-muted-foreground' };+ const sign = d > 0 ? '+' : '−';+ const cls = d > 0 ? 'text-rose-600 dark:text-rose-400' : 'text-emerald-600 dark:text-emerald-400';+ return { text: `${sign}${formatValue(unit, Math.abs(d))}`, cls };+ }+</script>++{#if rows.length}+ <div class="overflow-hidden rounded-lg border" data-testid="top-functions">+ <Table.Root>+ <Table.Header>+ <Table.Row>+ <TracewayTableHeader label="Function" />+ <TracewayTableHeader+ label="Flat"+ tooltip="Time spent inside this function itself (self)"+ align="right"+ sortField="flat"+ currentSortField={sortField}+ {sortDirection}+ {onSort}+ />+ <TracewayTableHeader label="Flat %" align="right" />+ {#if baselineRows}+ <TracewayTableHeader label="Δ Flat" tooltip="Change in flat vs baseline" align="right" />+ {/if}+ <TracewayTableHeader+ label="Cumulative"+ tooltip="Time spent in this function and everything it calls"+ align="right"+ sortField="cum"+ currentSortField={sortField}+ {sortDirection}+ {onSort}+ />+ <TracewayTableHeader label="Cum %" align="right" />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each visible as row (row.name)}+ <Table.Row+ class={onSelect ? 'cursor-pointer hover:bg-muted/50' : ''}+ onclick={onSelect ? () => onSelect(row.name) : undefined}+ >+ <Table.Cell class="max-w-[28rem] truncate font-mono text-xs" title={row.name}>+ {row.name}+ </Table.Cell>+ <Table.Cell class="text-right tabular-nums">+ {formatValue(unit, row.flat)}+ </Table.Cell>+ <Table.Cell class="text-right tabular-nums text-muted-foreground">+ {pct(row.flatPct)}+ </Table.Cell>+ {#if baselineRows}+ {@const d = deltaLabel(row)}+ <Table.Cell class="text-right tabular-nums {d.cls}">{d.text}</Table.Cell>+ {/if}+ <Table.Cell class="text-right tabular-nums">+ {formatValue(unit, row.cum)}+ </Table.Cell>+ <Table.Cell>+ <div class="flex items-center justify-end gap-2">+ <div class="h-1.5 w-16 shrink-0 overflow-hidden rounded bg-muted">+ <div class="h-full bg-primary" style="width: {Math.min(100, row.cumPct)}%"></div>+ </div>+ <span class="w-12 text-right tabular-nums text-muted-foreground">{pct(row.cumPct)}</span>+ </div>+ </Table.Cell>+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ {#if sorted.length > COLLAPSED}+ <div class="border-t p-2 text-center">+ <Button variant="ghost" size="sm" onclick={() => (expanded = !expanded)}>+ {expanded ? 'Show less' : `Show all ${sorted.length}`}+ </Button>+ </div>+ {/if}+ </div>+{/if}diff --git a/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelte b/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelteindex 631bf057..8bbef809 100644--- a/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelte+++ b/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelte@@ -147,11 +147,11 @@const [toHour, toMinute] = toTime.split(':').map(Number);tempFromDateTime = new CalendarDateTime(fromDate.year, fromDate.month, fromDate.day,- fromHour || 0, fromMinute || 0, 0+ Number.isFinite(fromHour) ? fromHour : 0, Number.isFinite(fromMinute) ? fromMinute : 0, 0);tempToDateTime = new CalendarDateTime(toDate.year, toDate.month, toDate.day,- toHour || 23, toMinute || 59, 0+ Number.isFinite(toHour) ? toHour : 23, Number.isFinite(toMinute) ? toMinute : 59, 0);}}diff --git a/frontend/src/lib/components/ui/tooltip/tooltip-content.svelte b/frontend/src/lib/components/ui/tooltip/tooltip-content.svelteindex 01cd4bcf..42c4cc8c 100644--- a/frontend/src/lib/components/ui/tooltip/tooltip-content.svelte+++ b/frontend/src/lib/components/ui/tooltip/tooltip-content.svelte@@ -27,7 +27,7 @@{sideOffset}{side}class={cn(- 'z-50 max-w-[220px] origin-(--bits-tooltip-content-transform-origin) animate-in rounded-sm border bg-foreground px-3 py-2 text-xs text-background shadow-[none] fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95',+ 'z-50 max-w-[220px] origin-(--bits-tooltip-content-transform-origin) animate-in rounded-sm border border-transparent bg-foreground px-3 py-2 text-xs text-background shadow-[none] fade-in-0 zoom-in-95 dark:border-border data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-end-2 data-[side=right]:slide-in-from-start-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95',className)}{...restProps}@@ -37,7 +37,7 @@{#snippet child({ props })}<divclass={cn(- 'z-50 size-2.5 rotate-45 border-border bg-foreground',+ 'z-50 size-2.5 rotate-45 border-transparent bg-foreground dark:border-border','data-[side=top]:border-r data-[side=top]:border-b','data-[side=bottom]:border-t data-[side=bottom]:border-l','data-[side=left]:border-r data-[side=left]:border-b',diff --git a/frontend/src/lib/utils/flame-diff.test.ts b/frontend/src/lib/utils/flame-diff.test.tsnew file mode 100644index 00000000..e9e444b1--- /dev/null+++ b/frontend/src/lib/utils/flame-diff.test.ts@@ -0,0 +1,50 @@+import { describe, it, expect } from 'vitest';+import { mergeFlameTrees } from './flame-diff';++describe('mergeFlameTrees', () => {+ it('returns null when there is no current tree', () => {+ expect(mergeFlameTrees({ name: 'root', value: 10 }, null)).toBeNull();+ });++ it('computes delta as the difference of normalized fractions', () => {+ const base = {+ name: 'root',+ value: 100,+ children: [+ { name: 'a', value: 50 },+ { name: 'b', value: 50 }+ ]+ };+ const cur = {+ name: 'root',+ value: 200,+ children: [+ { name: 'a', value: 150 },+ { name: 'b', value: 50 }+ ]+ };+ const merged = mergeFlameTrees(base, cur)!;+ expect(merged.value).toBe(200);+ const a = merged.children!.find((c) => c.name === 'a')!;+ const b = merged.children!.find((c) => c.name === 'b')!;+ // a: 150/200 - 50/100 = 0.75 - 0.5 = 0.25 (hotter)+ expect(a.delta).toBeCloseTo(0.25, 5);+ // b: 50/200 - 50/100 = 0.25 - 0.5 = -0.25 (cooler)+ expect(b.delta).toBeCloseTo(-0.25, 5);+ });++ it('treats frames absent from the baseline as fully added (positive delta)', () => {+ const base = { name: 'root', value: 100, children: [{ name: 'a', value: 100 }] };+ const cur = {+ name: 'root',+ value: 100,+ children: [+ { name: 'a', value: 60 },+ { name: 'new', value: 40 }+ ]+ };+ const merged = mergeFlameTrees(base, cur)!;+ const added = merged.children!.find((c) => c.name === 'new')!;+ expect(added.delta).toBeCloseTo(0.4, 5);+ });+});diff --git a/frontend/src/lib/utils/flame-diff.ts b/frontend/src/lib/utils/flame-diff.tsnew file mode 100644index 00000000..aace7441--- /dev/null+++ b/frontend/src/lib/utils/flame-diff.ts@@ -0,0 +1,32 @@+import type { FlameGraphNode } from 'd3-flame-graph';++function buildDiffNode(+ curNode: FlameGraphNode,+ baseNode: FlameGraphNode | undefined,+ curTotal: number,+ baseTotal: number+): FlameGraphNode {+ const curFrac = curTotal > 0 ? curNode.value / curTotal : 0;+ const baseFrac = baseNode && baseTotal > 0 ? baseNode.value / baseTotal : 0;++ const baseChildren = new Map<string, FlameGraphNode>();+ for (const c of baseNode?.children ?? []) baseChildren.set(c.name, c);++ return {+ name: curNode.name,+ value: curNode.value,+ self: curNode.self,+ delta: curFrac - baseFrac,+ children: (curNode.children ?? []).map((c) =>+ buildDiffNode(c, baseChildren.get(c.name), curTotal, baseTotal)+ )+ };+}++export function mergeFlameTrees(+ base: FlameGraphNode | null,+ cur: FlameGraphNode | null+): FlameGraphNode | null {+ if (!cur) return null;+ return buildDiffNode(cur, base ?? undefined, cur.value || 0, base?.value || 0);+}diff --git a/frontend/src/lib/utils/flame-ops.ts b/frontend/src/lib/utils/flame-ops.tsnew file mode 100644index 00000000..a58e8a1c--- /dev/null+++ b/frontend/src/lib/utils/flame-ops.ts@@ -0,0 +1,112 @@+import type { FlameGraphNode } from 'd3-flame-graph';++function deepClone(node: FlameGraphNode): FlameGraphNode {+ return {+ name: node.name,+ value: node.value,+ self: node.self ?? 0,+ children: (node.children ?? []).map(deepClone)+ };+}++function sortTree(node: FlameGraphNode): void {+ if (!node.children) return;+ node.children.sort((a, b) => b.value - a.value || a.name.localeCompare(b.name));+ for (const c of node.children) sortTree(c);+}++export function collapseRecursion(node: FlameGraphNode): FlameGraphNode {+ const out: FlameGraphNode = { name: node.name, value: node.value, self: node.self ?? 0, children: [] };+ const byName = new Map<string, FlameGraphNode>();++ const addChild = (c: FlameGraphNode) => {+ if (c.name === out.name) {+ out.self = (out.self ?? 0) + (c.self ?? 0);+ for (const gc of c.children ?? []) addChild(gc);+ return;+ }+ const existing = byName.get(c.name);+ if (existing) {+ existing.value += c.value;+ existing.self = (existing.self ?? 0) + (c.self ?? 0);+ existing.children = [...(existing.children ?? []), ...(c.children ?? [])];+ } else {+ const copy: FlameGraphNode = {+ name: c.name,+ value: c.value,+ self: c.self ?? 0,+ children: [...(c.children ?? [])]+ };+ byName.set(c.name, copy);+ out.children!.push(copy);+ }+ };++ for (const c of node.children ?? []) addChild(c);+ out.children = out.children!.map(collapseRecursion);+ return out;+}++export interface Sandwich {+ fn: string;+ callers: FlameGraphNode;+ callees: FlameGraphNode;+ total: number;+}++function mergeInto(target: FlameGraphNode, src: FlameGraphNode): void {+ target.value += src.value;+ target.self = (target.self ?? 0) + (src.self ?? 0);+ const byName = new Map<string, FlameGraphNode>();+ for (const c of target.children ?? []) byName.set(c.name, c);+ for (const sc of src.children ?? []) {+ const existing = byName.get(sc.name);+ if (existing) {+ mergeInto(existing, sc);+ } else {+ const copy = deepClone(sc);+ byName.set(sc.name, copy);+ (target.children ??= []).push(copy);+ }+ }+}++export function buildSandwich(root: FlameGraphNode | null, fn: string): Sandwich | null {+ if (!root) return null;++ const calleeRoot: FlameGraphNode = { name: fn, value: 0, self: 0, children: [] };+ const callerRoot: FlameGraphNode = { name: fn, value: 0, self: 0, children: [] };++ const walk = (node: FlameGraphNode, ancestors: FlameGraphNode[]) => {+ if (node.name === fn) {+ mergeInto(calleeRoot, {+ name: fn,+ value: node.value,+ self: node.self ?? 0,+ children: node.children ?? []+ });++ let cursor = callerRoot;+ cursor.value += node.value;+ for (let i = ancestors.length - 1; i >= 0; i--) {+ const a = ancestors[i];+ let child = (cursor.children ?? []).find((c) => c.name === a.name);+ if (!child) {+ child = { name: a.name, value: 0, self: 0, children: [] };+ (cursor.children ??= []).push(child);+ }+ child.value += node.value;+ cursor = child;+ }+ return;+ }+ for (const c of node.children ?? []) walk(c, [...ancestors, node]);+ };++ walk(root, []);+ if (calleeRoot.value === 0) return null;++ sortTree(callerRoot);+ sortTree(calleeRoot);+ return { fn, callers: callerRoot, callees: calleeRoot, total: calleeRoot.value };+}diff --git a/frontend/src/lib/utils/profile-format.test.ts b/frontend/src/lib/utils/profile-format.test.tsindex c6138b9d..1654f82d 100644--- a/frontend/src/lib/utils/profile-format.test.ts+++ b/frontend/src/lib/utils/profile-format.test.ts@@ -1,66 +1,56 @@import { describe, it, expect } from 'vitest';-import {- CPU_NANOS,- HEAP_INUSE,- HEAP_ALLOC,- getProfileTypeMeta,- formatProfileValue,- defaultProfileType-} from './profile-format';+import { formatValue, humanizeType, defaultProfileType } from './profile-format';-describe('getProfileTypeMeta', () => {- it('returns meta for the CPU type', () => {- const meta = getProfileTypeMeta(CPU_NANOS);- expect(meta).toMatchObject({ category: 'cpu', unit: 'nanoseconds', isGauge: false });- expect(meta?.label).toBeTruthy();+describe('formatValue', () => {+ it('formats time units, normalizing to a readable scale', () => {+ expect(formatValue('nanoseconds', 500)).toBe('500 ns');+ expect(formatValue('nanoseconds', 1_500)).toBe('1.5 µs');+ expect(formatValue('milliseconds', 1_500)).toBe('1.5 s');+ expect(formatValue('microseconds', 2_000)).toBe('2 ms');+ expect(formatValue('seconds', 3)).toBe('3 s');});- it('marks heap in-use as a gauge', () => {- const meta = getProfileTypeMeta(HEAP_INUSE);- expect(meta).toMatchObject({ category: 'heap', unit: 'bytes', isGauge: true });+ it('formats byte units', () => {+ expect(formatValue('bytes', 512)).toBe('512 B');+ expect(formatValue('bytes', 1024)).toBe('1 KB');+ expect(formatValue('bytes', 1_048_576)).toBe('1 MB');});- it('marks heap alloc as a counter (not a gauge)', () => {- const meta = getProfileTypeMeta(HEAP_ALLOC);- expect(meta).toMatchObject({ category: 'heap', unit: 'bytes', isGauge: false });+ it('formats count-like units as localized integers', () => {+ expect(formatValue('count', 1500)).toBe((1500).toLocaleString());+ expect(formatValue('samples', 42)).toBe('42');+ expect(formatValue('', 7)).toBe('7');});- it('returns undefined for an unknown type', () => {- expect(getProfileTypeMeta('go:profile_mutex:contentions')).toBeUndefined();+ it('falls back to a localized number plus the raw unit for unknown units', () => {+ expect(formatValue('widgets', 1234)).toBe(`${(1234).toLocaleString()} widgets`);});});-describe('formatProfileValue', () => {- it('formats CPU nanoseconds across magnitudes', () => {- expect(formatProfileValue(CPU_NANOS, 500)).toBe('500 ns');- expect(formatProfileValue(CPU_NANOS, 1_500)).toBe('1.5 µs');- expect(formatProfileValue(CPU_NANOS, 1_500_000)).toBe('1.5 ms');- expect(formatProfileValue(CPU_NANOS, 2_000_000_000)).toBe('2 s');- expect(formatProfileValue(CPU_NANOS, 0)).toBe('0 ns');+describe('humanizeType', () => {+ it('uses short friendly labels for the well-known pprof names', () => {+ expect(humanizeType('cpu')).toBe('CPU');+ expect(humanizeType('inuse_space')).toBe('In-Use');+ expect(humanizeType('goroutine')).toBe('Goroutines');+ expect(humanizeType('lock')).toBe('Lock');});- it('formats heap bytes across magnitudes', () => {- expect(formatProfileValue(HEAP_INUSE, 512)).toBe('512 B');- expect(formatProfileValue(HEAP_INUSE, 1024)).toBe('1 KB');- expect(formatProfileValue(HEAP_ALLOC, 1_048_576)).toBe('1 MB');- expect(formatProfileValue(HEAP_INUSE, 0)).toBe('0 B');- });-- it('falls back to a localized number for unknown types', () => {- expect(formatProfileValue('go:profile_mystery:units', 1234)).toBe((1234).toLocaleString());+ it('title-cases arbitrary cross-language type names', () => {+ expect(humanizeType('async_profiler_wall')).toBe('Async Profiler Wall');+ expect(humanizeType('jvm:heap_live')).toBe('Heap Live');});});describe('defaultProfileType', () => {- it('prefers the CPU type when available', () => {- expect(defaultProfileType([HEAP_INUSE, CPU_NANOS, HEAP_ALLOC])).toBe(CPU_NANOS);+ it('prefers cpu when present', () => {+ expect(defaultProfileType(['inuse_space', 'cpu', 'lock'])).toBe('cpu');});- it('falls back to the first available type when there is no CPU type', () => {- expect(defaultProfileType([HEAP_ALLOC, HEAP_INUSE])).toBe(HEAP_ALLOC);+ it('falls back to the first available type', () => {+ expect(defaultProfileType(['lock', 'wall'])).toBe('lock');});- it('returns an empty string when nothing is available', () => {+ it('returns empty string when nothing is available', () => {expect(defaultProfileType([])).toBe('');});});diff --git a/frontend/src/lib/utils/profile-format.ts b/frontend/src/lib/utils/profile-format.tsindex c83ad74d..b13b97bd 100644--- a/frontend/src/lib/utils/profile-format.ts+++ b/frontend/src/lib/utils/profile-format.ts@@ -1,30 +1,9 @@-export const CPU_NANOS = 'go:profile_cpu:nanoseconds';-export const HEAP_INUSE = 'go:profile_heap:inuse_space';-export const HEAP_ALLOC = 'go:profile_heap:alloc_space';--export type ProfileCategory = 'cpu' | 'heap';-export type ProfileUnit = 'nanoseconds' | 'bytes';--export interface ProfileTypeMeta {+export interface ProfileTypeInfo {type: string;- label: string;- category: ProfileCategory;- unit: ProfileUnit;+ unit: string;isGauge: boolean;}-export const PROFILE_TYPES: ProfileTypeMeta[] = [- { type: CPU_NANOS, label: 'CPU Time', category: 'cpu', unit: 'nanoseconds', isGauge: false },- { type: HEAP_INUSE, label: 'Heap In-Use', category: 'heap', unit: 'bytes', isGauge: true },- { type: HEAP_ALLOC, label: 'Heap Allocations', category: 'heap', unit: 'bytes', isGauge: false }-];--const TYPE_INDEX = new Map(PROFILE_TYPES.map((meta) => [meta.type, meta]));--export function getProfileTypeMeta(type: string): ProfileTypeMeta | undefined {- return TYPE_INDEX.get(type);-}-function trim(value: number): string {return Number(value.toFixed(2)).toString();}@@ -43,14 +22,73 @@ function formatBytes(bytes: number): string {return `${trim(bytes / 1024 ** 3)} GB`;}-export function formatProfileValue(type: string, value: number): string {- const meta = getProfileTypeMeta(type);- if (meta?.unit === 'nanoseconds') return formatNanoseconds(value);- if (meta?.unit === 'bytes') return formatBytes(value);- return value.toLocaleString();+const TIME_TO_NS: Record<string, number> = {+ nanoseconds: 1,+ nanos: 1,+ ns: 1,+ microseconds: 1_000,+ micros: 1_000,+ us: 1_000,+ µs: 1_000,+ milliseconds: 1_000_000,+ millis: 1_000_000,+ ms: 1_000_000,+ seconds: 1_000_000_000,+ s: 1_000_000_000+};++const BYTE_UNITS = new Set(['bytes', 'byte', 'b']);+const COUNT_UNITS = new Set(['count', 'samples', 'sample', 'frames', 'objects', 'goroutines', 'none', '']);++export function formatValue(unit: string, value: number): string {+ const u = (unit || '').toLowerCase();+ if (u in TIME_TO_NS) return formatNanoseconds(value * TIME_TO_NS[u]);+ if (BYTE_UNITS.has(u)) return formatBytes(value);+ if (COUNT_UNITS.has(u)) return Math.round(value).toLocaleString();+ return `${value.toLocaleString()} ${unit}`.trim();+}++const KNOWN_LABELS: Record<string, string> = {+ cpu: 'CPU',+ inuse_space: 'In-Use',+ alloc_space: 'Alloc',+ inuse_objects: 'In-Use Obj',+ alloc_objects: 'Alloc Obj',+ goroutine: 'Goroutines',+ mutex: 'Mutex',+ block: 'Block',+ samples: 'Samples',+ wall: 'Wall',+ lock: 'Lock'+};++export function humanizeType(type: string): string {+ if (KNOWN_LABELS[type]) return KNOWN_LABELS[type];+ const tail = type.includes(':') ? (type.split(':').pop() ?? type) : type;+ return tail+ .replace(/[._]/g, ' ')+ .split(' ')+ .filter(Boolean)+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))+ .join(' ');+}++export function defaultProfileType(types: string[]): string {+ if (types.includes('cpu')) return 'cpu';+ return types[0] ?? '';+}++export function isTimeUnit(unit: string): boolean {+ return (unit || '').toLowerCase() in TIME_TO_NS;}-export function defaultProfileType(availableTypes: string[]): string {- if (availableTypes.includes(CPU_NANOS)) return CPU_NANOS;- return availableTypes[0] ?? '';+export function formatRate(unit: string, value: number): string {+ const u = (unit || '').toLowerCase();+ if (u in TIME_TO_NS) {+ const cores = (value * TIME_TO_NS[u]) / 1_000_000_000;+ return `${trim(cores)} cores`;+ }+ if (BYTE_UNITS.has(u)) return `${formatBytes(value)}/s`;+ if (COUNT_UNITS.has(u)) return `${Math.round(value).toLocaleString()}/s`;+ return `${value.toLocaleString()} ${unit}/s`.trim();}diff --git a/frontend/src/routes/profiles/+page.svelte b/frontend/src/routes/profiles/+page.svelteindex 08c0936d..547ea43f 100644--- a/frontend/src/routes/profiles/+page.svelte+++ b/frontend/src/routes/profiles/+page.svelte@@ -2,10 +2,11 @@import { onMount, onDestroy } from 'svelte';import { api } from '$lib/api';import { formatRelativeTime, toUTCISO, calendarDateTimeToLuxon } from '$lib/utils/formatters';- import { formatProfileValue, getProfileTypeMeta } from '$lib/utils/profile-format';+ import { formatValue, humanizeType } from '$lib/utils/profile-format';import { getTimezone } from '$lib/state/timezone.svelte';import * as Table from '$lib/components/ui/table';import { LoadingCircle } from '$lib/components/ui/loading-circle';+ import { SearchBar } from '$lib/components/ui/search-bar';import { TracewayTableHeader } from '$lib/components/ui/traceway-table-header';import { TableEmptyState } from '$lib/components/ui/table-empty-state';import { PaginationFooter } from '$lib/components/ui/pagination-footer';@@ -35,10 +36,13 @@type ProfileGroup = {serviceName: string;type: string;+ unit: string;+ isGauge: boolean;profileCount: number;sampleCount: number;totalValue: number;lastSeen: string;+ sparkline?: number[];};type SortField = 'profile_count' | 'sample_count' | 'total_value' | 'last_seen';@@ -51,6 +55,21 @@let pageSize = $state(50);let total = $state(0);let totalPages = $state(0);+ let search = $state('');++ function handleSearch() {+ page = 1;+ loadData(false);+ }++ function sparkPath(values: number[]): string {+ if (!values || values.length < 2) return '';+ const max = Math.max(...values, 1);+ const step = 100 / (values.length - 1);+ return values+ .map((v, i) => `${i === 0 ? 'M' : 'L'} ${(i * step).toFixed(1)} ${(16 - (v / max) * 15).toFixed(1)}`)+ .join(' ');+ }const initialUrlParams = parseTimeRangeFromUrl(timezone);const initialRange = getResolvedTimeRange(initialUrlParams, timezone);@@ -128,7 +147,7 @@}function typeLabel(type: string): string {- return getProfileTypeMeta(type)?.label ?? type;+ return humanizeType(type);}function detailHref(group: ProfileGroup): string {@@ -155,6 +174,7 @@toDate: getToDateTimeUTC(),orderBy,sortDirection,+ search,pagination: { page, pageSize }};@@ -208,10 +228,10 @@</script><div class="space-y-4">- <div class="flex flex-col gap-4 sm:flex-row sm:justify-between">+ <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between"><PageHeader title="Profiles" />- <div class="flex flex-col">+ <div class="w-full sm:w-auto"><TimeRangePickerbind:fromDatebind:toDate@@ -223,12 +243,19 @@</div></div>+ <SearchBar+ placeholder="Search services..."+ bind:value={search}+ onSearch={handleSearch}+ disabled={loading}+ />+<div class="overflow-hidden rounded-md border"><Table.Root>{#if loading}<Table.Body><Table.Row>- <Table.Cell colspan={6} class="h-48">+ <Table.Cell colspan={7} class="h-48"><div class="flex h-full items-center justify-center"><LoadingCircle size="xlg" /></div>@@ -238,12 +265,12 @@{:else if error}<Table.Body><Table.Row>- <Table.Cell colspan={6} class="h-24 text-center text-red-500">{error}</Table.Cell>+ <Table.Cell colspan={7} class="h-24 text-center text-red-500">{error}</Table.Cell></Table.Row></Table.Body>{:else if groups.length === 0}<Table.Body>- <TableEmptyState colspan={6} message="No profile data received yet" />+ <TableEmptyState colspan={7} message="No profile data received yet" /></Table.Body>{:else}<Table.Header>@@ -280,6 +307,11 @@onSort={(field) => handleSort(field as SortField)}class="w-[120px]"/>+ <TracewayTableHeader+ label="Trend"+ tooltip="Total trend across the selected range"+ class="w-[120px]"+ /><TracewayTableHeaderlabel="Last Seen"tooltip="When this service last reported this profile type"@@ -302,7 +334,26 @@<Table.Cell class="tabular-nums">{formatCount(group.profileCount)}</Table.Cell><Table.Cell class="tabular-nums">{formatCount(group.sampleCount)}</Table.Cell><Table.Cell class="font-mono text-sm tabular-nums">- {formatProfileValue(group.type, group.totalValue)}+ {formatValue(group.unit, group.totalValue)}+ </Table.Cell>+ <Table.Cell>+ {#if group.sparkline && group.sparkline.length > 1}+ <svg+ viewBox="0 0 100 16"+ preserveAspectRatio="none"+ class="h-5 w-24 text-primary"+ >+ <path+ d={sparkPath(group.sparkline)}+ fill="none"+ stroke="currentColor"+ stroke-width="1.5"+ vector-effect="non-scaling-stroke"+ />+ </svg>+ {:else}+ <span class="text-xs text-muted-foreground">—</span>+ {/if}</Table.Cell><Table.Cell class="text-sm text-muted-foreground">{formatRelativeTime(group.lastSeen, timezone)}diff --git a/frontend/src/routes/profiles/[service]/+page.svelte b/frontend/src/routes/profiles/[service]/+page.svelteindex 2035ea95..5d68f9af 100644--- a/frontend/src/routes/profiles/[service]/+page.svelte+++ b/frontend/src/routes/profiles/[service]/+page.svelte@@ -1,31 +1,42 @@<script lang="ts">- import { onMount } from 'svelte';+ import { onMount, onDestroy } from 'svelte';import { api } from '$lib/api';+ import { authState } from '$lib/state/auth.svelte';+ import { toast } from 'svelte-sonner';import { Button } from '$lib/components/ui/button';import { LoadingCircle } from '$lib/components/ui/loading-circle';import { TimeRangePicker } from '$lib/components/ui/time-range-picker';import { ErrorDisplay } from '$lib/components/ui/error-display';import * as Tabs from '$lib/components/ui/tabs';- import { ArrowLeft } from '@lucide/svelte';+ import * as Select from '$lib/components/ui/select';+ import { ArrowLeft, GitCompareArrows, Download, Layers, Gauge, X } from '@lucide/svelte';import { goto } from '$app/navigation';import { resolve } from '$app/paths';import { projectsState } from '$lib/state/projects.svelte';import PageHeader from '$lib/components/issues/page-header.svelte';import FlameGraph from '$lib/components/profiles/flame-graph.svelte';+ import ProfileSeriesChart, {+ type SeriesPoint,+ type SeriesGroup+ } from '$lib/components/profiles/profile-series-chart.svelte';+ import TopFunctionsTable, {+ type FunctionStat+ } from '$lib/components/profiles/top-functions-table.svelte';import TagFilter from '$lib/components/dashboard/tag-filter.svelte';+ import { mergeFlameTrees } from '$lib/utils/flame-diff';+ import { collapseRecursion, buildSandwich } from '$lib/utils/flame-ops';import { CalendarDate } from '@internationalized/date';import {- PROFILE_TYPES,defaultProfileType,- formatProfileValue,- getProfileTypeMeta,- type ProfileTypeMeta+ formatValue,+ formatRate,+ isTimeUnit,+ humanizeType,+ type ProfileTypeInfo} from '$lib/utils/profile-format';import {presetMinutes,getTimeRangeFromPreset,- parseTimeRangeFromUrl,- getResolvedTimeRange,dateToCalendarDate,dateToTimeString,updateUrl@@ -36,23 +47,64 @@const timezone = $derived(getTimezone());- type SeriesPoint = { timestamp: string; value: number };-let { data } = $props();let flameData = $state<FlameGraphNode | null>(null);let series = $state<SeriesPoint[]>([]);+ let breakdown = $state<SeriesGroup[]>([]);let totalValue = $state(0);let availableLabels = $state<Record<string, string[]>>({});let selectedLabels = $state<Record<string, string>>({});+ let topFunctions = $state<FunctionStat[]>([]);+ let dimensions = $state<{ appVersions: string[]; serverNames: string[] }>({+ appVersions: [],+ serverNames: []+ });let loading = $state(true);let error = $state('');let notFound = $state(false);- const knownTypes = PROFILE_TYPES.map((t) => t.type);- let activeType = $state(- data.type && knownTypes.includes(data.type) ? data.type : defaultProfileType(knownTypes)- );+ let flameSearch = $state('');+ let selectedFrame = $state<string | null>(null);+ let collapseRecursionOn = $state(false);+ let normalize = $state(false);+ let groupBy = $state('');++ let compareMode = $state(false);+ let diffView = $state<'differential' | 'sidebyside'>('differential');+ let baseFlameData = $state<FlameGraphNode | null>(null);+ let baseTopFunctions = $state<FunctionStat[]>([]);+ let diffData = $state<FlameGraphNode | null>(null);+ let baseAppVersion = $state('');+ let baseServerName = $state('');+ let downloading = $state(false);++ let availableTypes = $state<ProfileTypeInfo[]>([]);+ let activeType = $state(data.type ?? '');++ let tabsListEl = $state<HTMLElement | null>(null);+ let hasOverflow = $state(false);++ function checkOverflow() {+ if (tabsListEl) {+ hasOverflow = tabsListEl.scrollWidth > tabsListEl.clientWidth;+ }+ }++ $effect(() => {+ if (!tabsListEl) return;+ const observer = new ResizeObserver(() => checkOverflow());+ observer.observe(tabsListEl);+ checkOverflow();+ return () => observer.disconnect();+ });++ $effect(() => {+ availableTypes;+ if (tabsListEl) {+ requestAnimationFrame(() => checkOverflow());+ }+ });function getInitialRange(): { preset: string | null; from: Date; to: Date } {if (data.preset && presetMinutes[data.preset]) {@@ -78,8 +130,39 @@let fromTime = $state(dateToTimeString(initialRange.from, timezone));let toTime = $state(dateToTimeString(initialRange.to, timezone));- const activeMeta = $derived<ProfileTypeMeta | undefined>(getProfileTypeMeta(activeType));+ const baseInitial = getTimeRangeFromPreset('7d', timezone);+ let baseSelectedPreset = $state<string | null>('7d');+ let baseFromDate = $state<CalendarDate>(dateToCalendarDate(baseInitial.from, timezone));+ let baseToDate = $state<CalendarDate>(dateToCalendarDate(baseInitial.to, timezone));+ let baseFromTime = $state(dateToTimeString(baseInitial.from, timezone));+ let baseToTime = $state(dateToTimeString(baseInitial.to, timezone));++ const activeMeta = $derived<ProfileTypeInfo | undefined>(+ availableTypes.find((t) => t.type === activeType)+ );+ const activeUnit = $derived(activeMeta?.unit ?? '');+ const activeIsGauge = $derived(activeMeta?.isGauge ?? false);const seriesPeak = $derived(series.reduce((max, p) => Math.max(max, p.value), 0));+ const rateActive = $derived(normalize && !activeIsGauge);+ const rateUnitIsTime = $derived(isTimeUnit(activeUnit));+ const rateToggleLabel = $derived(rateUnitIsTime ? 'Cores' : 'Per second');++ const mainFlame = $derived(+ collapseRecursionOn && flameData ? collapseRecursion(flameData) : flameData+ );+ const sandwich = $derived.by(() =>+ selectedFrame ? buildSandwich(flameData, selectedFrame) : null+ );++ const groupByOptions = $derived([+ { value: '', label: 'No grouping' },+ { value: 'app_version', label: 'App version' },+ { value: 'server_name', label: 'Server' },+ ...Object.keys(availableLabels).map((k) => ({ value: `label:${k}`, label: k }))+ ]);+ const groupByLabel = $derived(+ groupByOptions.find((o) => o.value === groupBy)?.label ?? 'No grouping'+ );function updateUrlParams(pushToHistory = true) {const params: Record<string, string | undefined> = selectedPreset@@ -94,7 +177,7 @@const dt = calendarDateTimeToLuxon({ year: fromDate.year, month: fromDate.month, day: fromDate.day, hour, minute },timezone- );+ ).startOf('minute');return toUTCISO(dt);}@@ -115,6 +198,39 @@return Math.max(1, Math.round(spanMinutes / 60));}+ function syncRangeFromUrl(): boolean {+ if (typeof window === 'undefined') return false;+ const params = new URLSearchParams(window.location.search);+ const presetParam = params.get('preset');+ const fromParam = params.get('from');+ const toParam = params.get('to');+ const typeParam = params.get('type');+ if (typeParam) activeType = typeParam;++ if (presetParam && presetMinutes[presetParam]) {+ selectedPreset = presetParam;+ return true;+ }+ if (fromParam && toParam) {+ const fromDt = parseISO(fromParam, timezone);+ const toDt = parseISO(toParam, timezone);+ if (fromDt.isValid && toDt.isValid) {+ selectedPreset = null;+ fromDate = dateToCalendarDate(fromDt.toJSDate(), timezone);+ fromTime = dateToTimeString(fromDt.toJSDate(), timezone);+ toDate = dateToCalendarDate(toDt.toJSDate(), timezone);+ toTime = dateToTimeString(toDt.toJSDate(), timezone);+ return true;+ }+ }+ return true;+ }++ function handlePopState() {+ syncRangeFromUrl();+ loadData(false);+ }+function handleTimeRangeChange(from: { date: CalendarDate; time: string },to: { date: CalendarDate; time: string },@@ -128,9 +244,23 @@loadData(true);}+ function handleBrushSelect(fromIso: string, toIso: string) {+ const fromDt = parseISO(fromIso, timezone);+ const toDt = parseISO(toIso, timezone);+ if (!fromDt.isValid || !toDt.isValid) return;+ selectedPreset = null;+ fromDate = dateToCalendarDate(fromDt.toJSDate(), timezone);+ fromTime = dateToTimeString(fromDt.toJSDate(), timezone);+ toDate = dateToCalendarDate(toDt.toJSDate(), timezone);+ toTime = dateToTimeString(toDt.toJSDate(), timezone);+ loadData(true);+ }+function handleTypeChange(type: string) {activeType = type;selectedLabels = {};+ groupBy = '';+ selectedFrame = null;loadData(true);}@@ -139,6 +269,10 @@loadData(true);}+ function focusFrame(name: string) {+ flameSearch = name;+ }+async function loadData(pushToHistory = true) {loading = true;error = '';@@ -152,38 +286,80 @@toTime = dateToTimeString(range.to, timezone);}- updateUrlParams(pushToHistory);-const fromIso = getFromDateTimeUTC();const toIso = getToDateTimeUTC();- const body = {- fromDate: fromIso,- toDate: toIso,- serviceName: data.service,- type: activeType- };+ const projectId = projectsState.currentProjectId ?? undefined;try {- const [tree, points, labels] = await Promise.all([- api.post(- '/profiles/flamegraph',- { ...body, labels: selectedLabels },- { projectId: projectsState.currentProjectId ?? undefined }- ),+ const types = (await api+ .post(+ '/profiles/types',+ { fromDate: fromIso, toDate: toIso, serviceName: data.service },+ { projectId }+ )+ .catch(() => [])) as ProfileTypeInfo[];+ availableTypes = types || [];++ const typeNames = availableTypes.map((t) => t.type);+ if (!activeType || !typeNames.includes(activeType)) {+ activeType = defaultProfileType(typeNames);+ }+ const isGauge = availableTypes.find((t) => t.type === activeType)?.isGauge ?? false;++ updateUrlParams(pushToHistory);++ const body = {+ fromDate: fromIso,+ toDate: toIso,+ serviceName: data.service,+ type: activeType+ };+ const interval = intervalMinutes(fromIso, toIso);++ const [tree, points, labels, top, dims, groups] = await Promise.all([+ api.post('/profiles/flamegraph', { ...body, isGauge, labels: selectedLabels }, { projectId }),api.post('/profiles/series',- { ...body, intervalMinutes: intervalMinutes(fromIso, toIso) },- { projectId: projectsState.currentProjectId ?? undefined }+ { ...body, isGauge, intervalMinutes: interval, labels: selectedLabels, normalize },+ { projectId }),- api.post('/profiles/labels', body, {- projectId: projectsState.currentProjectId ?? undefined- }).catch(() => ({}))+ api.post('/profiles/labels', body, { projectId }).catch(() => ({})),+ api+ .post('/profiles/top', { ...body, isGauge, labels: selectedLabels, limit: 100 }, { projectId })+ .catch(() => []),+ api.post('/profiles/dimensions', body, { projectId }).catch(() => ({})),+ groupBy+ ? api+ .post(+ '/profiles/series/breakdown',+ {+ ...body,+ isGauge,+ intervalMinutes: interval,+ labels: selectedLabels,+ normalize,+ dimension: groupBy,+ limit: 8+ },+ { projectId }+ )+ .catch(() => [])+ : Promise.resolve([])]);totalValue = tree?.value ?? 0;flameData = tree?.children?.length ? tree : null;series = points || [];availableLabels = labels || {};+ topFunctions = (top as FunctionStat[]) || [];+ dimensions = {+ appVersions: dims?.appVersions ?? [],+ serverNames: dims?.serverNames ?? []+ };+ breakdown = (groups as SeriesGroup[]) || [];+ if (selectedFrame && !flameData) selectedFrame = null;++ if (compareMode) await loadCompare(isGauge);} catch (e: any) {if (e?.status === 404) {notFound = true;@@ -196,20 +372,131 @@}}- const sparkPath = $derived.by(() => {- if (series.length < 2 || seriesPeak === 0) return '';- const step = 100 / (series.length - 1);- return series- .map(- (p, i) =>- `${i === 0 ? 'M' : 'L'} ${(i * step).toFixed(2)} ${(30 - (p.value / seriesPeak) * 28).toFixed(2)}`- )- .join(' ');- });+ function baseRangeFromUTC(): string {+ if (baseSelectedPreset) {+ return getTimeRangeFromPreset(baseSelectedPreset, timezone).from.toISOString();+ }+ const [hour, minute] = (baseFromTime || '00:00').split(':').map(Number);+ return toUTCISO(+ calendarDateTimeToLuxon(+ { year: baseFromDate.year, month: baseFromDate.month, day: baseFromDate.day, hour, minute },+ timezone+ ).startOf('minute')+ );+ }++ function baseRangeToUTC(): string {+ if (baseSelectedPreset) {+ return getTimeRangeFromPreset(baseSelectedPreset, timezone).to.toISOString();+ }+ const [hour, minute] = (baseToTime || '23:59').split(':').map(Number);+ return toUTCISO(+ calendarDateTimeToLuxon(+ { year: baseToDate.year, month: baseToDate.month, day: baseToDate.day, hour, minute },+ timezone+ ).endOf('minute')+ );+ }++ async function loadCompare(isGauge: boolean) {+ const projectId = projectsState.currentProjectId ?? undefined;+ const baseBody = {+ fromDate: baseRangeFromUTC(),+ toDate: baseRangeToUTC(),+ serviceName: data.service,+ type: activeType,+ isGauge,+ labels: selectedLabels,+ appVersion: baseAppVersion,+ serverName: baseServerName+ };+ try {+ const [baseTree, baseTop] = await Promise.all([+ api.post('/profiles/flamegraph', baseBody, { projectId }),+ api.post('/profiles/top', { ...baseBody, limit: 100 }, { projectId }).catch(() => [])+ ]);+ baseFlameData = baseTree?.children?.length ? baseTree : null;+ baseTopFunctions = (baseTop as FunctionStat[]) || [];+ diffData = mergeFlameTrees(baseFlameData, flameData);+ } catch (e) {+ console.error(e);+ baseFlameData = null;+ baseTopFunctions = [];+ diffData = null;+ }+ }++ function toggleCompare() {+ compareMode = !compareMode;+ if (compareMode) loadCompare(activeIsGauge);+ }++ function handleBaseRangeChange(+ from: { date: CalendarDate; time: string },+ to: { date: CalendarDate; time: string },+ preset: string | null+ ) {+ baseFromDate = from.date;+ baseFromTime = from.time;+ baseToDate = to.date;+ baseToTime = to.time;+ baseSelectedPreset = preset;+ loadCompare(activeIsGauge);+ }++ async function downloadPprof() {+ if (!flameData) return;+ downloading = true;+ try {+ const projectId = projectsState.currentProjectId;+ const url = `/api/profiles/pprof${projectId ? `?projectId=${projectId}` : ''}`;+ const res = await fetch(url, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ ...(authState.token ? { Authorization: `Bearer ${authState.token}` } : {})+ },+ body: JSON.stringify({+ fromDate: getFromDateTimeUTC(),+ toDate: getToDateTimeUTC(),+ serviceName: data.service,+ type: activeType,+ unit: activeUnit,+ isGauge: activeIsGauge,+ labels: selectedLabels+ })+ });+ if (!res.ok) {+ toast.error('Failed to export profile', { position: 'top-center' });+ return;+ }+ const blob = await res.blob();+ const objectUrl = URL.createObjectURL(blob);+ const anchor = document.createElement('a');+ anchor.href = objectUrl;+ anchor.download = `${data.service}-${activeType.replace(/[^a-zA-Z0-9-_]/g, '_')}.pprof`;+ document.body.appendChild(anchor);+ anchor.click();+ anchor.remove();+ URL.revokeObjectURL(objectUrl);+ } catch (e) {+ console.error(e);+ toast.error('Failed to export profile', { position: 'top-center' });+ } finally {+ downloading = false;+ }+ }onMount(() => {+ window.addEventListener('popstate', handlePopState);loadData(false);});++ onDestroy(() => {+ if (typeof window !== 'undefined') {+ window.removeEventListener('popstate', handlePopState);+ }+ });</script><div class="space-y-4">@@ -233,20 +520,91 @@</div></div>- <Tabs.Root value={activeType} onValueChange={handleTypeChange}>- <Tabs.List>- {#each PROFILE_TYPES as meta (meta.type)}- <Tabs.Trigger value={meta.type}>{meta.label}</Tabs.Trigger>- {/each}- </Tabs.List>- </Tabs.Root>-- <TagFilter- tagKeys={Object.keys(availableLabels)}- activeFilters={selectedLabels}- onFilterChange={handleFilterChange}- onLoadTagValues={(key) => Promise.resolve(availableLabels[key] ?? [])}- />+ {#if availableTypes.length}+ <Tabs.Root value={activeType} onValueChange={handleTypeChange}>+ <div class="flex items-center" class:gap-2={!hasOverflow}>+ {#if hasOverflow}+ <Select.Root+ type="single"+ value={activeType}+ onValueChange={(v) => {+ if (v) handleTypeChange(v);+ }}+ >+ <Select.Trigger size="sm" class="w-full" data-testid="type-overflow-select">+ {activeType ? humanizeType(activeType) : 'Select type'}+ </Select.Trigger>+ <Select.Content>+ {#each availableTypes as meta (meta.type)}+ <Select.Item value={meta.type}>{humanizeType(meta.type)}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ {/if}+ <div+ class="flex min-w-0 items-center overflow-hidden"+ class:invisible={hasOverflow}+ class:h-0={hasOverflow}+ class:w-0={hasOverflow}+ bind:this={tabsListEl}+ >+ <Tabs.List>+ {#each availableTypes as meta (meta.type)}+ <Tabs.Trigger value={meta.type}>{humanizeType(meta.type)}</Tabs.Trigger>+ {/each}+ </Tabs.List>+ </div>+ </div>+ </Tabs.Root>+ {/if}++ <div class="flex flex-wrap items-center gap-2">+ <TagFilter+ tagKeys={Object.keys(availableLabels)}+ activeFilters={selectedLabels}+ onFilterChange={handleFilterChange}+ onLoadTagValues={(key) => Promise.resolve(availableLabels[key] ?? [])}+ />++ <div class="flex-1"></div>++ <Select.Root+ type="single"+ value={groupBy}+ onValueChange={(v) => {+ groupBy = v ?? '';+ loadData(false);+ }}+ >+ <Select.Trigger size="sm" class="w-44" data-testid="group-by-select">+ Group by: {groupByLabel}+ </Select.Trigger>+ <Select.Content>+ {#each groupByOptions as opt (opt.value)}+ <Select.Item value={opt.value}>{opt.label}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>++ {#if !activeIsGauge}+ <Button+ variant={normalize ? 'secondary' : 'outline'}+ size="sm"+ aria-pressed={normalize}+ onclick={() => {+ normalize = !normalize;+ loadData(false);+ }}+ data-testid="normalize-toggle"+ title={rateUnitIsTime+ ? 'Show CPU as cores in use (CPU time per wall-second)'+ : 'Show as a per-second rate'}+ >+ <Gauge class="h-4 w-4" />+ {rateToggleLabel}+ </Button>+ {/if}+ </div>{#if loading}<div class="flex items-center justify-center py-20">@@ -262,43 +620,218 @@{:else if error}<ErrorDisplay status={400} title="Error" description={error} onRetry={() => loadData()} />{:else}- <div class="grid gap-4 sm:grid-cols-3">+ <div class="grid gap-4 sm:grid-cols-2"><div class="rounded-lg border p-4"><div class="text-sm text-muted-foreground">- Total {activeMeta?.category === 'heap' ? 'Memory' : 'CPU Time'}+ Total {activeType ? humanizeType(activeType) : ''}</div><div class="text-2xl font-bold tabular-nums">- {formatProfileValue(activeType, totalValue)}+ {formatValue(activeUnit, totalValue)}</div></div><div class="rounded-lg border p-4"><div class="text-sm text-muted-foreground">- Peak {activeMeta?.isGauge ? '(avg/bucket)' : '(sum/bucket)'}+ Peak {rateActive+ ? rateUnitIsTime+ ? '(utilization)'+ : '(rate)'+ : activeIsGauge+ ? '(avg/bucket)'+ : '(sum/bucket)'}</div><div class="text-2xl font-bold tabular-nums">- {formatProfileValue(activeType, seriesPeak)}+ {rateActive ? formatRate(activeUnit, seriesPeak) : formatValue(activeUnit, seriesPeak)}</div></div>- <div class="rounded-lg border p-4">- <div class="text-sm text-muted-foreground">Trend</div>- {#if sparkPath}- <svg viewBox="0 0 100 30" preserveAspectRatio="none" class="mt-1 h-9 w-full text-primary">- <path- d={sparkPath}- fill="none"- stroke="currentColor"- stroke-width="1.5"- vector-effect="non-scaling-stroke"- />- </svg>- {:else}- <div class="mt-1 text-sm text-muted-foreground">Not enough data</div>- {/if}- </div></div><div class="rounded-lg border p-4">- <FlameGraph data={flameData} type={activeType} />+ <div class="mb-1 text-sm text-muted-foreground">+ Trend{groupBy ? ` · by ${groupByLabel.toLowerCase()}` : ''}+ </div>+ <ProfileSeriesChart+ series={groupBy ? [] : series}+ groups={groupBy ? breakdown : []}+ unit={activeUnit}+ isRate={rateActive}+ onSelectRange={handleBrushSelect}+ />+ </div>++ <div class="space-y-3 rounded-lg border p-4">+ <div class="flex flex-wrap items-center gap-2">+ <Button+ variant={compareMode ? 'secondary' : 'outline'}+ size="sm"+ aria-pressed={compareMode}+ onclick={toggleCompare}+ data-testid="compare-toggle"+ >+ <GitCompareArrows class="h-4 w-4" />+ Compare+ </Button>++ <Button+ variant={collapseRecursionOn ? 'secondary' : 'outline'}+ size="sm"+ aria-pressed={collapseRecursionOn}+ onclick={() => (collapseRecursionOn = !collapseRecursionOn)}+ data-testid="collapse-recursion"+ title="Collapse direct recursion in the flame graph"+ >+ <Layers class="h-4 w-4" />+ Collapse recursion+ </Button>++ <div class="flex-1"></div>++ {#if compareMode}+ <div class="flex gap-1">+ <Button+ variant={diffView === 'differential' ? 'secondary' : 'outline'}+ size="sm"+ onclick={() => (diffView = 'differential')}+ data-testid="diff-differential"+ >+ Differential+ </Button>+ <Button+ variant={diffView === 'sidebyside' ? 'secondary' : 'outline'}+ size="sm"+ onclick={() => (diffView = 'sidebyside')}+ data-testid="diff-sidebyside"+ >+ Side by side+ </Button>+ </div>+ {/if}++ <Button+ variant="outline"+ size="sm"+ onclick={downloadPprof}+ disabled={downloading || !flameData}+ data-testid="download-pprof"+ >+ <Download class="h-4 w-4" />+ Download .pprof+ </Button>+ </div>++ {#if compareMode}+ <div class="flex flex-wrap items-center gap-2 rounded-md bg-muted/40 p-2">+ <span class="text-xs font-medium text-muted-foreground">Baseline:</span>+ <TimeRangePicker+ bind:fromDate={baseFromDate}+ bind:toDate={baseToDate}+ bind:fromTime={baseFromTime}+ bind:toTime={baseToTime}+ bind:preset={baseSelectedPreset}+ onApply={handleBaseRangeChange}+ />+ <Select.Root+ type="single"+ value={baseAppVersion}+ onValueChange={(v) => {+ baseAppVersion = v ?? '';+ loadCompare(activeIsGauge);+ }}+ >+ <Select.Trigger size="sm" class="w-40" data-testid="base-app-version">+ {baseAppVersion || 'All versions'}+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="">All versions</Select.Item>+ {#each dimensions.appVersions as v (v)}+ <Select.Item value={v}>{v}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ <Select.Root+ type="single"+ value={baseServerName}+ onValueChange={(v) => {+ baseServerName = v ?? '';+ loadCompare(activeIsGauge);+ }}+ >+ <Select.Trigger size="sm" class="w-40" data-testid="base-server">+ {baseServerName || 'All servers'}+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="">All servers</Select.Item>+ {#each dimensions.serverNames as s (s)}+ <Select.Item value={s}>{s}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>+ {/if}++ {#if compareMode && diffView === 'differential'}+ <div class="flex items-center gap-4 text-xs text-muted-foreground">+ <span class="inline-flex items-center gap-1.5">+ <span class="h-2.5 w-3.5 rounded-sm" style="background: hsl(8, 70%, 55%)"></span>+ hotter than baseline+ </span>+ <span class="inline-flex items-center gap-1.5">+ <span class="h-2.5 w-3.5 rounded-sm" style="background: hsl(140, 60%, 50%)"></span>+ cooler than baseline+ </span>+ </div>+ <FlameGraph data={diffData} unit={activeUnit} diff={true} />+ {:else if compareMode}+ <div class="grid gap-4 lg:grid-cols-2">+ <div>+ <div class="mb-1 text-xs font-medium text-muted-foreground">Baseline</div>+ <FlameGraph data={baseFlameData} unit={activeUnit} controls={false} />+ </div>+ <div>+ <div class="mb-1 text-xs font-medium text-muted-foreground">Current</div>+ <FlameGraph data={mainFlame} unit={activeUnit} controls={false} />+ </div>+ </div>+ {:else}+ <FlameGraph+ data={mainFlame}+ unit={activeUnit}+ bind:searchTerm={flameSearch}+ onFrameSelect={(name) => (selectedFrame = name)}+ />+ {/if}</div>++ {#if sandwich && !compareMode}+ <div class="space-y-3 rounded-lg border p-4">+ <div class="flex items-center justify-between gap-2">+ <div class="min-w-0">+ <div class="text-sm font-medium">Function detail</div>+ <div class="truncate font-mono text-xs text-muted-foreground" title={sandwich.fn}>+ {sandwich.fn} · {formatValue(activeUnit, sandwich.total)}+ </div>+ </div>+ <Button variant="ghost" size="sm" onclick={() => (selectedFrame = null)} title="Close">+ <X class="h-4 w-4" />+ </Button>+ </div>+ <div class="grid gap-4 lg:grid-cols-2">+ <div>+ <div class="mb-1 text-xs font-medium text-muted-foreground">Callers</div>+ <FlameGraph data={sandwich.callers} unit={activeUnit} controls={false} inverted={true} />+ </div>+ <div>+ <div class="mb-1 text-xs font-medium text-muted-foreground">Callees</div>+ <FlameGraph data={sandwich.callees} unit={activeUnit} controls={false} />+ </div>+ </div>+ </div>+ {/if}++ <TopFunctionsTable+ rows={topFunctions}+ unit={activeUnit}+ onSelect={focusFrame}+ baselineRows={compareMode ? baseTopFunctions : undefined}+ />{/if}</div>diff --git a/testing/profiles-e2e/ingest/profiles-e2e-ingest b/testing/profiles-e2e/ingest/profiles-e2e-ingestnew file mode 100755index 00000000..c4238acbBinary files /dev/null and b/testing/profiles-e2e/ingest/profiles-e2e-ingest differ