Skip to content

The only tool you need to know what is happening and how to fix it.

feat(profiling): retention TTLs, optional raw archive, disk cleanup (PR 5) (#233)

FrameAutomata876c506783ad
diff --git a/CLAUDE.md b/CLAUDE.md
index d754fa1d..be90865e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -257,6 +257,8 @@ NOTIFICATION_POLL_SECONDS=60 # polled rule evaluation interval; minimum
# Retention (see "Data Retention" section below)
SQLITE_RETENTION_DAYS=30 # 0 to disable; only applies in SQLite mode
SESSION_RECORDING_RETENTION_DAYS=30 # 0 to disable; only applies when STORAGE_TYPE=local
+PROFILE_ARCHIVE_RAW=false # native pprof ingest only: write the original pprof bytes to object storage as a lossless archive
+PROFILE_RETENTION_DAYS=30 # 0 to disable; on-disk archive TTL, only with PROFILE_ARCHIVE_RAW + STORAGE_TYPE=local
# Session recording uploads (see "Session Recording Uploader" section below)
SESSION_RECORDING_UPLOAD_WORKERS=32 # 0 to disable uploads entirely
@@ -754,8 +756,13 @@ Retention is handled in three different ways depending on the deployment.
| `metric_points_1m` (1-min rollup) | **30 days** | `0035_add_ttl_metric_points_1m.up.sql` |
| `metric_points_1h` (1-hour rollup) | **1 year** | `0036_add_ttl_metric_points_1h.up.sql` |
| `log_records` | **30 days** | `0045_create_log_records.up.sql` |
+| `profiling_samples` (the bulk) | **30 days** | `0068_add_ttl_profiling_samples.up.sql` |
+| `profiles` (slim metadata) | **30 days** | `0069_add_ttl_profiles.up.sql` |
+| `profiling_stacks` (dedup table) | **30 days** | `0070_add_ttl_profiling_stacks.up.sql` |
| All other CH tables (`transactions`, `exception_stack_traces`, `tasks`, `spans`, `sessions`, `ai_traces`, `session_recordings`, `fired_notifications`, `archived_exceptions`, `slow_endpoints`, `endpoints`, etc.) | **No TTL — retained indefinitely** | — |
+The three profiling tables share a 30-day TTL keyed on each table's time column (`start_time` / `recorded_at` / `last_seen`). `profiling_stacks` is a `ReplacingMergeTree(last_seen)` dedup table, so `last_seen` is bumped on every re-ingest that references a stack — a stack only ages out once it has gone unreferenced for the full window, which is exactly when its samples have also expired, so no sample is ever left pointing at a dropped stack.
+
**2. SQLite — `retention.Start` worker** (`backend/app/retention/sqlite.go`). In SQLite mode, neither `db.DB` nor `db.TelemetryDB` has any built-in expiry, so a background worker fires once at startup and then every hour and runs a `DELETE FROM <table> WHERE <time_column> < cutoff` against each telemetry table.
| Variable | Default | Notes |
@@ -770,8 +777,11 @@ Tables it prunes (and the column used):
| Telemetry | `log_records` | `timestamp` |
| Telemetry | `sessions` | `started_at` |
| Telemetry | `fired_notifications` | `fired_at` |
+| Telemetry | `profiling_samples` | `start_time` |
+| Telemetry | `profiles` | `recorded_at` |
+| Telemetry | `profiling_stacks` | `last_seen` |
-`archived_exceptions` (per-hash flags) and `slow_endpoints` (per-endpoint config) are intentionally skipped — they are not time-series data.
+`archived_exceptions` (per-hash flags) and `slow_endpoints` (per-endpoint config) are intentionally skipped — they are not time-series data. `profiling_stacks` *is* pruned (unlike those two) because it holds no user intent — it is a regenerable dedup table whose `last_seen` tracks the most recent referencing sample, so deleting expired stacks is safe.
**3. On-disk session recordings — `retention.Start` worker** (`backend/app/retention/recordings.go`). Session recordings written to local disk (`STORAGE_TYPE=local`) accumulate under `<STORAGE_PATH>/recordings/`. A second worker walks that directory once at startup and then every hour and removes files whose `mtime` is older than the TTL, then prunes any directories left empty. The worker is a no-op when `STORAGE_TYPE=s3`.
@@ -781,6 +791,15 @@ Tables it prunes (and the column used):
The DB rows in `session_recordings` are pruned by the SQLite retention worker (above) or by ClickHouse TTL — they are intentionally not coupled to the disk cleanup. Controllers that read recordings already log a non-fatal `traceway.CaptureException` when a referenced file is missing.
+**4. On-disk raw profile archives — `retention.Start` worker** (`backend/app/retention/profiles.go`). When `PROFILE_ARCHIVE_RAW` is enabled, the **native pprof ingest path** (`/profiles/ingest`) writes each upload's original pprof bytes to `<STORAGE_PATH>/profiles/<projectId>/<yyyymmdd>/<id>.pprof` (recorded on `Profile.StorageKey`) as a lossless archive for download / re-ingest / PGO — off the read path. The OTLP endpoint does not archive (its rows carry an empty `StorageKey`). A worker walks that directory once at startup and then every hour and removes files whose `mtime` is older than the TTL, then prunes empty directories. It reuses the same generic age-based cleanup as the recordings worker (`runDirAgeCleanup` / `isSafeStorageSubdir`) and is a no-op unless `PROFILE_ARCHIVE_RAW` is on **and** `STORAGE_TYPE=local`.
+
+| Variable | Default | Notes |
+|----------|---------|-------|
+| `PROFILE_ARCHIVE_RAW` | `false` | Master switch for the raw archive. When off, no blob is written and the disk worker does nothing. |
+| `PROFILE_RETENTION_DAYS` | `30` | TTL in days for the on-disk archive. Set to `0` to disable the disk worker. Only runs when `PROFILE_ARCHIVE_RAW` is on and `STORAGE_TYPE=local`. |
+
+The `profiles` DB rows (and their `storage_key`) are pruned by the SQLite retention worker / ClickHouse TTL above — not coupled to this disk cleanup, mirroring the session-recording split.
+
#### Session Recording Uploader
Session recording segments arriving on `/api/report` are not uploaded inline. The handler enqueues each segment onto a bounded worker pool (`backend/app/recordings/uploader.go`, started from `cmd/run.go` next to `retention.Start`). Workers drain the queue and write the body via `storage.Store.Write` (S3 or local disk); successful writes are handed to a single batcher goroutine that calls `SessionRecordingRepository.InsertAsync` once per ~1000 rows or every 2 s, whichever comes first — single-row inserts are an anti-pattern for ClickHouse. Enqueue is non-blocking: when the queue is full the segment is dropped (newest-first) so a burst of `/api/report` traffic cannot spawn unbounded goroutines or saturate S3.
diff --git a/backend/app/config/config.go b/backend/app/config/config.go
index 798a0122..7c4976f1 100644
--- a/backend/app/config/config.go
+++ b/backend/app/config/config.go
@@ -33,6 +33,9 @@ type Cfg struct {
SessionRecordingUploadWorkers string
SessionRecordingUploadQueueSize string
+ ProfileArchiveRaw string
+ ProfileRetentionDays string
+
SourceMapCacheMaxEntries string
SourceMapCacheMaxBytesMB string
SourceMapCacheType string
@@ -114,6 +117,9 @@ func LoadFromEnv() *Cfg {
SessionRecordingUploadWorkers: os.Getenv("SESSION_RECORDING_UPLOAD_WORKERS"),
SessionRecordingUploadQueueSize: os.Getenv("SESSION_RECORDING_UPLOAD_QUEUE_SIZE"),
+ ProfileArchiveRaw: os.Getenv("PROFILE_ARCHIVE_RAW"),
+ ProfileRetentionDays: os.Getenv("PROFILE_RETENTION_DAYS"),
+
SourceMapCacheMaxEntries: os.Getenv("SOURCEMAP_CACHE_MAX_ENTRIES"),
SourceMapCacheMaxBytesMB: os.Getenv("SOURCEMAP_CACHE_MAX_BYTES_MB"),
SourceMapCacheType: os.Getenv("SOURCEMAP_CACHE_TYPE"),
diff --git a/backend/app/controllers/clientcontrollers/profile_ingest.controller.go b/backend/app/controllers/clientcontrollers/profile_ingest.controller.go
index d85f35e5..da6e43a6 100644
--- a/backend/app/controllers/clientcontrollers/profile_ingest.controller.go
+++ b/backend/app/controllers/clientcontrollers/profile_ingest.controller.go
@@ -1,6 +1,8 @@
package clientcontrollers
import (
+ "context"
+ "fmt"
"io"
"net/http"
"time"
@@ -12,6 +14,7 @@ import (
"github.com/tracewayapp/traceway/backend/app/monitoring"
"github.com/tracewayapp/traceway/backend/app/profiling"
"github.com/tracewayapp/traceway/backend/app/repositories"
+ "github.com/tracewayapp/traceway/backend/app/storage"
traceway "go.tracewayapp.com"
)
@@ -69,6 +72,7 @@ func (e profileIngestController) Ingest(c *gin.Context) {
convertStart := time.Now()
stacks, samples, profiles := profiling.BuildRows(projectId, decoded)
+ archiveKey, archive := profiling.StampArchive(projectId, ingestCtx.ReceivedAt, profiles)
convertMs := float64(time.Since(convertStart).Microseconds()) / 1000.0
insertStart := time.Now()
@@ -86,6 +90,15 @@ func (e profileIngestController) Ingest(c *gin.Context) {
}
insertMs := float64(time.Since(insertStart).Microseconds()) / 1000.0
+ if archive {
+ go func() {
+ defer traceway.Recover()
+ if err := storage.Store.Write(context.Background(), archiveKey, body); err != nil {
+ traceway.CaptureException(fmt.Errorf("failed to write profile archive (key=%s): %w", archiveKey, err))
+ }
+ }()
+ }
+
monitoring.RecordIngestBatch(monitoring.SignalNative, "profiles", convertMs, insertMs, len(samples), len(body))
c.JSON(http.StatusOK, gin.H{})
diff --git a/backend/app/controllers/clientcontrollers/profile_ingest_controller_test.go b/backend/app/controllers/clientcontrollers/profile_ingest_controller_test.go
index 4458efc7..a9a09317 100644
--- a/backend/app/controllers/clientcontrollers/profile_ingest_controller_test.go
+++ b/backend/app/controllers/clientcontrollers/profile_ingest_controller_test.go
@@ -4,18 +4,23 @@ package clientcontrollers
import (
"bytes"
+ "context"
"database/sql"
"net/http"
"net/http/httptest"
+ "sync"
"testing"
+ "time"
"github.com/gin-gonic/gin"
"github.com/google/pprof/profile"
"github.com/google/uuid"
"github.com/tracewayapp/lit/v2"
+ "github.com/tracewayapp/traceway/backend/app/config"
"github.com/tracewayapp/traceway/backend/app/db"
"github.com/tracewayapp/traceway/backend/app/middleware"
"github.com/tracewayapp/traceway/backend/app/models"
+ "github.com/tracewayapp/traceway/backend/app/storage"
_ "modernc.org/sqlite"
)
@@ -165,3 +170,90 @@ func TestProfileIngest_RejectsGarbage(t *testing.T) {
t.Fatalf("status = %d, want 400 for garbage body", w.Code)
}
}
+
+type fakeStore struct {
+ mu sync.Mutex
+ written map[string][]byte
+ writes chan string
+}
+
+func (f *fakeStore) Write(_ context.Context, key string, data []byte) error {
+ f.mu.Lock()
+ f.written[key] = append([]byte(nil), data...)
+ f.mu.Unlock()
+ f.writes <- key
+ return nil
+}
+
+func (f *fakeStore) Read(_ context.Context, _ string) ([]byte, error) { return nil, nil }
+func (f *fakeStore) Delete(_ context.Context, _ string) error { return nil }
+
+func TestProfileIngest_ArchivesRawWhenEnabled(t *testing.T) {
+ setupProfilingDB(t)
+
+ prevCfg, prevStore := config.Config, storage.Store
+ t.Cleanup(func() { config.Config, storage.Store = prevCfg, prevStore })
+ config.Config = &config.Cfg{ProfileArchiveRaw: "true"}
+ fs := &fakeStore{written: map[string][]byte{}, writes: make(chan string, 1)}
+ storage.Store = fs
+
+ projectId := uuid.New()
+ body := cpuPprof(t)
+ c, w := newIngestContext(t, projectId, "checkout-svc", "/profiles/ingest", body)
+
+ ProfileIngestController.Ingest(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
+ }
+
+ var storageKey string
+ db.TelemetryDB.QueryRow("SELECT storage_key FROM profiles LIMIT 1").Scan(&storageKey)
+ if storageKey == "" {
+ t.Fatal("storage_key not persisted on profile row when archiving enabled")
+ }
+
+ select {
+ case key := <-fs.writes:
+ if key != storageKey {
+ t.Errorf("archived under %q, but profile row points at %q", key, storageKey)
+ }
+ fs.mu.Lock()
+ got := fs.written[key]
+ fs.mu.Unlock()
+ if !bytes.Equal(got, body) {
+ t.Errorf("archived bytes (%d) != uploaded pprof body (%d)", len(got), len(body))
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("raw archive write did not occur")
+ }
+}
+
+func TestProfileIngest_NoArchiveWhenDisabled(t *testing.T) {
+ setupProfilingDB(t)
+
+ prevCfg, prevStore := config.Config, storage.Store
+ t.Cleanup(func() { config.Config, storage.Store = prevCfg, prevStore })
+ config.Config = &config.Cfg{ProfileArchiveRaw: ""}
+ fs := &fakeStore{written: map[string][]byte{}, writes: make(chan string, 1)}
+ storage.Store = fs
+
+ projectId := uuid.New()
+ c, w := newIngestContext(t, projectId, "checkout-svc", "/profiles/ingest", cpuPprof(t))
+
+ ProfileIngestController.Ingest(c)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
+ }
+
+ var storageKey string
+ db.TelemetryDB.QueryRow("SELECT storage_key FROM profiles LIMIT 1").Scan(&storageKey)
+ if storageKey != "" {
+ t.Errorf("storage_key = %q, want empty when archiving disabled", storageKey)
+ }
+
+ select {
+ case key := <-fs.writes:
+ t.Errorf("unexpected archive write to %q when archiving disabled", key)
+ case <-time.After(200 * time.Millisecond):
+ }
+}
diff --git a/backend/app/migrations/ch/0068_add_ttl_profiling_samples.up.sql b/backend/app/migrations/ch/0068_add_ttl_profiling_samples.up.sql
new file mode 100644
index 00000000..d2c50365
--- /dev/null
+++ b/backend/app/migrations/ch/0068_add_ttl_profiling_samples.up.sql
@@ -0,0 +1 @@
+ALTER TABLE profiling_samples MODIFY TTL toDateTime(start_time) + INTERVAL 30 DAY
diff --git a/backend/app/migrations/ch/0069_add_ttl_profiles.up.sql b/backend/app/migrations/ch/0069_add_ttl_profiles.up.sql
new file mode 100644
index 00000000..2aabc708
--- /dev/null
+++ b/backend/app/migrations/ch/0069_add_ttl_profiles.up.sql
@@ -0,0 +1 @@
+ALTER TABLE profiles MODIFY TTL toDateTime(recorded_at) + INTERVAL 30 DAY
diff --git a/backend/app/migrations/ch/0070_add_ttl_profiling_stacks.up.sql b/backend/app/migrations/ch/0070_add_ttl_profiling_stacks.up.sql
new file mode 100644
index 00000000..e9f36442
--- /dev/null
+++ b/backend/app/migrations/ch/0070_add_ttl_profiling_stacks.up.sql
@@ -0,0 +1 @@
+ALTER TABLE profiling_stacks MODIFY TTL toDateTime(last_seen) + INTERVAL 30 DAY
diff --git a/backend/app/profiling/archive.go b/backend/app/profiling/archive.go
new file mode 100644
index 00000000..ebff1cfb
--- /dev/null
+++ b/backend/app/profiling/archive.go
@@ -0,0 +1,39 @@
+package profiling
+
+import (
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+
+ "github.com/tracewayapp/traceway/backend/app/config"
+ "github.com/tracewayapp/traceway/backend/app/models"
+)
+
+func ArchiveKey(projectId, profileId uuid.UUID, recordedAt time.Time) string {
+ day := recordedAt.UTC().Format("20060102")
+ return "profiles/" + projectId.String() + "/" + day + "/" + profileId.String() + ".pprof"
+}
+
+func RawArchiveEnabled() bool {
+ if config.Config == nil {
+ return false
+ }
+ enabled, err := strconv.ParseBool(strings.TrimSpace(config.Config.ProfileArchiveRaw))
+ if err != nil {
+ return false
+ }
+ return enabled
+}
+
+func StampArchive(projectId uuid.UUID, recordedAt time.Time, profiles []models.Profile) (string, bool) {
+ if !RawArchiveEnabled() || len(profiles) == 0 {
+ return "", false
+ }
+ key := ArchiveKey(projectId, uuid.New(), recordedAt)
+ for i := range profiles {
+ profiles[i].StorageKey = key
+ }
+ return key, true
+}
diff --git a/backend/app/profiling/archive_test.go b/backend/app/profiling/archive_test.go
new file mode 100644
index 00000000..f00dcb9c
--- /dev/null
+++ b/backend/app/profiling/archive_test.go
@@ -0,0 +1,119 @@
+package profiling
+
+import (
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/tracewayapp/traceway/backend/app/config"
+ "github.com/tracewayapp/traceway/backend/app/models"
+)
+
+func TestArchiveKey(t *testing.T) {
+ projectId := uuid.MustParse("11111111-1111-1111-1111-111111111111")
+ profileId := uuid.MustParse("22222222-2222-2222-2222-222222222222")
+ recordedAt := time.Date(2026, 6, 16, 10, 30, 0, 0, time.UTC)
+
+ got := ArchiveKey(projectId, profileId, recordedAt)
+ want := "profiles/11111111-1111-1111-1111-111111111111/20260616/22222222-2222-2222-2222-222222222222.pprof"
+
+ if got != want {
+ t.Errorf("ArchiveKey() = %q, want %q", got, want)
+ }
+}
+
+func TestArchiveKeyUsesUTCDate(t *testing.T) {
+ projectId := uuid.MustParse("11111111-1111-1111-1111-111111111111")
+ profileId := uuid.MustParse("22222222-2222-2222-2222-222222222222")
+
+ loc := time.FixedZone("UTC+2", 2*60*60)
+ recordedAt := time.Date(2026, 6, 17, 0, 30, 0, 0, loc)
+
+ got := ArchiveKey(projectId, profileId, recordedAt)
+ want := "profiles/11111111-1111-1111-1111-111111111111/20260616/22222222-2222-2222-2222-222222222222.pprof"
+
+ if got != want {
+ t.Errorf("ArchiveKey() = %q, want %q (date must be UTC-normalized)", got, want)
+ }
+}
+
+func TestRawArchiveEnabled(t *testing.T) {
+ prev := config.Config
+ t.Cleanup(func() { config.Config = prev })
+ config.Config = &config.Cfg{}
+
+ cases := []struct {
+ value string
+ want bool
+ }{
+ {"true", true},
+ {"1", true},
+ {"TRUE", true},
+ {"", false},
+ {"false", false},
+ {"0", false},
+ {"nonsense", false},
+ }
+
+ for _, c := range cases {
+ config.Config.ProfileArchiveRaw = c.value
+ if got := RawArchiveEnabled(); got != c.want {
+ t.Errorf("RawArchiveEnabled() with %q = %v, want %v", c.value, got, c.want)
+ }
+ }
+}
+
+func TestStampArchive(t *testing.T) {
+ prev := config.Config
+ t.Cleanup(func() { config.Config = prev })
+ config.Config = &config.Cfg{}
+
+ projectId := uuid.MustParse("11111111-1111-1111-1111-111111111111")
+ recordedAt := time.Date(2026, 6, 16, 10, 30, 0, 0, time.UTC)
+
+ t.Run("enabled stamps all rows with one key", func(t *testing.T) {
+ config.Config.ProfileArchiveRaw = "true"
+ profiles := []models.Profile{
+ {ProfileType: TypeHeapAllocSpace},
+ {ProfileType: TypeHeapInuseSpace},
+ }
+
+ key, ok := StampArchive(projectId, recordedAt, profiles)
+ if !ok {
+ t.Fatal("StampArchive ok = false, want true when enabled")
+ }
+ wantPrefix := "profiles/11111111-1111-1111-1111-111111111111/20260616/"
+ if len(key) < len(wantPrefix) || key[:len(wantPrefix)] != wantPrefix {
+ t.Errorf("key = %q, want prefix %q", key, wantPrefix)
+ }
+ if key[len(key)-6:] != ".pprof" {
+ t.Errorf("key = %q, want .pprof suffix", key)
+ }
+ for i, p := range profiles {
+ if p.StorageKey != key {
+ t.Errorf("profiles[%d].StorageKey = %q, want %q (all rows share one blob)", i, p.StorageKey, key)
+ }
+ }
+ })
+
+ t.Run("disabled is a no-op", func(t *testing.T) {
+ config.Config.ProfileArchiveRaw = "false"
+ profiles := []models.Profile{{ProfileType: TypeCPUNanos}}
+
+ key, ok := StampArchive(projectId, recordedAt, profiles)
+ if ok || key != "" {
+ t.Errorf("StampArchive = (%q, %v), want (\"\", false) when disabled", key, ok)
+ }
+ if profiles[0].StorageKey != "" {
+ t.Errorf("StorageKey = %q, want empty when disabled", profiles[0].StorageKey)
+ }
+ })
+
+ t.Run("no profiles is a no-op", func(t *testing.T) {
+ config.Config.ProfileArchiveRaw = "true"
+ key, ok := StampArchive(projectId, recordedAt, nil)
+ if ok || key != "" {
+ t.Errorf("StampArchive = (%q, %v), want (\"\", false) for empty profiles", key, ok)
+ }
+ })
+}
diff --git a/backend/app/retention/profiles.go b/backend/app/retention/profiles.go
new file mode 100644
index 00000000..870d6054
--- /dev/null
+++ b/backend/app/retention/profiles.go
@@ -0,0 +1,80 @@
+package retention
+
+import (
+ "context"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/tracewayapp/traceway/backend/app/config"
+ traceway "go.tracewayapp.com"
+)
+
+const profilesSubdir = "profiles"
+
+func profileArchiveDir(cfg *config.Cfg) (string, bool) {
+ if cfg == nil {
+ return "", false
+ }
+
+ enabled, err := strconv.ParseBool(strings.TrimSpace(cfg.ProfileArchiveRaw))
+ if err != nil || !enabled {
+ return "", false
+ }
+
+ storageType := cfg.StorageType
+ if storageType == "" {
+ storageType = "local"
+ }
+ if storageType != "local" {
+ return "", false
+ }
+
+ basePath := cfg.StoragePath
+ if basePath == "" {
+ basePath = "./storage"
+ }
+ abs, err := filepath.Abs(basePath)
+ if err != nil {
+ return "", false
+ }
+
+ dir := filepath.Clean(filepath.Join(abs, profilesSubdir))
+ if !isSafeStorageSubdir(dir) {
+ return "", false
+ }
+
+ return dir, true
+}
+
+func startProfileArchiveDiskCleanup(ctx context.Context, days int) {
+ if days == 0 {
+ config.Logln("Profile raw archive disk cleanup disabled (PROFILE_RETENTION_DAYS=0)")
+ return
+ }
+
+ dir, ok := profileArchiveDir(config.Config)
+ if !ok {
+ return
+ }
+
+ config.Logf("Starting profile raw archive disk cleanup worker (TTL: %d days, dir: %s)", days, dir)
+
+ go func() {
+ defer traceway.Recover()
+
+ runDirAgeCleanup(dir, days)
+
+ ticker := time.NewTicker(tickInterval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ runDirAgeCleanup(dir, days)
+ }
+ }
+ }()
+}
diff --git a/backend/app/retention/profiles_test.go b/backend/app/retention/profiles_test.go
new file mode 100644
index 00000000..0f3d91c7
--- /dev/null
+++ b/backend/app/retention/profiles_test.go
@@ -0,0 +1,67 @@
+package retention
+
+import (
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/tracewayapp/traceway/backend/app/config"
+)
+
+func TestProfileArchiveDir(t *testing.T) {
+ prev := config.Config
+ t.Cleanup(func() { config.Config = prev })
+ config.Config = &config.Cfg{}
+
+ cases := []struct {
+ name string
+ archiveRaw string
+ storageType string
+ storagePath string
+ wantOK bool
+ wantSuffix string
+ }{
+ {"disabled", "", "local", "/var/lib/traceway", false, ""},
+ {"enabled but s3", "true", "s3", "/var/lib/traceway", false, ""},
+ {"enabled local", "true", "local", "/var/lib/traceway", true, filepath.Join("traceway", "profiles")},
+ {"enabled default storage type", "true", "", "/var/lib/traceway", true, filepath.Join("traceway", "profiles")},
+ }
+
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ config.Config.ProfileArchiveRaw = c.archiveRaw
+ config.Config.StorageType = c.storageType
+ config.Config.StoragePath = c.storagePath
+
+ dir, ok := profileArchiveDir(config.Config)
+ if ok != c.wantOK {
+ t.Fatalf("profileArchiveDir ok = %v, want %v", ok, c.wantOK)
+ }
+ if ok {
+ if filepath.Base(dir) != profilesSubdir {
+ t.Errorf("profileArchiveDir dir = %q, want it to end in %q", dir, profilesSubdir)
+ }
+ if c.wantSuffix != "" && filepath.Base(filepath.Dir(dir))+string(filepath.Separator)+filepath.Base(dir) != c.wantSuffix {
+ t.Errorf("profileArchiveDir dir = %q, want suffix %q", dir, c.wantSuffix)
+ }
+ }
+ })
+ }
+}
+
+func TestRunProfileArchiveDiskCleanup_DeletesOldKeepsFresh(t *testing.T) {
+ dir := t.TempDir()
+
+ oldFile := filepath.Join(dir, "project-1", "20260101", "old.pprof")
+ freshFile := filepath.Join(dir, "project-1", "20260616", "fresh.pprof")
+
+ mustWriteFile(t, oldFile, "old")
+ mustWriteFile(t, freshFile, "fresh")
+
+ mustChtime(t, oldFile, time.Now().Add(-40*24*time.Hour))
+
+ runDirAgeCleanup(dir, 30)
+
+ assertNotExists(t, oldFile)
+ assertExists(t, freshFile)
+}
diff --git a/backend/app/retention/recordings.go b/backend/app/retention/recordings.go
index fafd6d28..0446a965 100644
--- a/backend/app/retention/recordings.go
+++ b/backend/app/retention/recordings.go
@@ -42,7 +42,7 @@ func startRecordingDiskCleanup(ctx context.Context, days int) {
}
recordingsDir := filepath.Clean(filepath.Join(abs, recordingsSubdir))
- if !isSafeRecordingsDir(recordingsDir) {
+ if !isSafeStorageSubdir(recordingsDir) {
traceway.CaptureException(fmt.Errorf("retention: refusing to clean shallow recordings dir %q — set STORAGE_PATH to a dedicated directory", recordingsDir))
return
}
@@ -52,7 +52,7 @@ func startRecordingDiskCleanup(ctx context.Context, days int) {
go func() {
defer traceway.Recover()
- runRecordingDiskCleanup(recordingsDir, days)
+ runDirAgeCleanup(recordingsDir, days)
ticker := time.NewTicker(tickInterval)
defer ticker.Stop()
@@ -61,13 +61,13 @@ func startRecordingDiskCleanup(ctx context.Context, days int) {
case <-ctx.Done():
return
case <-ticker.C:
- runRecordingDiskCleanup(recordingsDir, days)
+ runDirAgeCleanup(recordingsDir, days)
}
}
}()
}
-func isSafeRecordingsDir(path string) bool {
+func isSafeStorageSubdir(path string) bool {
cleaned := filepath.Clean(path)
if cleaned == "/" || cleaned == "." {
return false
@@ -77,7 +77,7 @@ func isSafeRecordingsDir(path string) bool {
return len(parts) >= 2
}
-func runRecordingDiskCleanup(dir string, days int) {
+func runDirAgeCleanup(dir string, days int) {
info, err := os.Stat(dir)
if errors.Is(err, fs.ErrNotExist) {
return
@@ -87,7 +87,7 @@ func runRecordingDiskCleanup(dir string, days int) {
return
}
if !info.IsDir() {
- traceway.CaptureException(fmt.Errorf("retention: recordings path %s is not a directory", dir))
+ traceway.CaptureException(fmt.Errorf("retention: cleanup path %s is not a directory", dir))
return
}
@@ -128,6 +128,6 @@ func runRecordingDiskCleanup(dir string, days int) {
}
if removed > 0 {
- config.Logf("Recording disk cleanup removed %d file(s) older than %d day(s) under %s", removed, days, dir)
+ config.Logf("Disk cleanup removed %d file(s) older than %d day(s) under %s", removed, days, dir)
}
}
diff --git a/backend/app/retention/recordings_test.go b/backend/app/retention/recordings_test.go
index 559c2bc5..b20b3612 100644
--- a/backend/app/retention/recordings_test.go
+++ b/backend/app/retention/recordings_test.go
@@ -7,7 +7,7 @@ import (
"time"
)
-func TestIsSafeRecordingsDir(t *testing.T) {
+func TestIsSafeStorageSubdir(t *testing.T) {
cases := []struct {
path string
safe bool
@@ -20,8 +20,8 @@ func TestIsSafeRecordingsDir(t *testing.T) {
{"/var/lib/traceway/recordings", true},
}
for _, c := range cases {
- if got := isSafeRecordingsDir(c.path); got != c.safe {
- t.Errorf("isSafeRecordingsDir(%q) = %v, want %v", c.path, got, c.safe)
+ if got := isSafeStorageSubdir(c.path); got != c.safe {
+ t.Errorf("isSafeStorageSubdir(%q) = %v, want %v", c.path, got, c.safe)
}
}
}
@@ -43,7 +43,7 @@ func TestRunRecordingDiskCleanup_DeletesOldKeepsFresh(t *testing.T) {
mustChtime(t, oldFile, aged)
mustChtime(t, nestedOld, aged)
- runRecordingDiskCleanup(dir, 30)
+ runDirAgeCleanup(dir, 30)
assertNotExists(t, oldFile)
assertExists(t, freshFile)
@@ -66,7 +66,7 @@ func TestRunRecordingDiskCleanup_PrunesEmptyDirsKeepsRoot(t *testing.T) {
mustChtime(t, emptyAfter, aged)
mustChtime(t, mixedOld, aged)
- runRecordingDiskCleanup(dir, 30)
+ runDirAgeCleanup(dir, 30)
assertExists(t, dir)
assertNotExists(t, filepath.Join(dir, "project-empty"))
@@ -78,7 +78,7 @@ func TestRunRecordingDiskCleanup_NoOpOnMissingDir(t *testing.T) {
parent := t.TempDir()
missing := filepath.Join(parent, "does-not-exist")
- runRecordingDiskCleanup(missing, 30)
+ runDirAgeCleanup(missing, 30)
if _, err := os.Stat(missing); !os.IsNotExist(err) {
t.Fatalf("expected missing dir to remain absent, got err=%v", err)
@@ -93,7 +93,7 @@ func TestRunRecordingDiskCleanup_RefusesPathThatIsAFile(t *testing.T) {
aged := time.Now().Add(-40 * 24 * time.Hour)
mustChtime(t, filePath, aged)
- runRecordingDiskCleanup(filePath, 30)
+ runDirAgeCleanup(filePath, 30)
assertExists(t, filePath)
}
@@ -110,7 +110,7 @@ func TestRunRecordingDiskCleanup_KeepsAllWhenNoneAreOld(t *testing.T) {
mustWriteFile(t, f, "fresh")
}
- runRecordingDiskCleanup(dir, 30)
+ runDirAgeCleanup(dir, 30)
for _, f := range files {
assertExists(t, f)
diff --git a/backend/app/retention/retention.go b/backend/app/retention/retention.go
index 61bf4952..0d0b47a8 100644
--- a/backend/app/retention/retention.go
+++ b/backend/app/retention/retention.go
@@ -16,25 +16,21 @@ const (
func Start(ctx context.Context) {
cfg := config.Config
- daysRetentionRecordings := defaultRetentionDays
- sessionRecordingRetentionDays := strings.TrimSpace(cfg.SessionRecordingRetentionDays)
- if sessionRecordingRetentionDays != "" {
- sessionRecordingRetentionDaysInt, err := strconv.Atoi(sessionRecordingRetentionDays)
- if err == nil && sessionRecordingRetentionDaysInt >= 0 {
- daysRetentionRecordings = sessionRecordingRetentionDaysInt
- }
- }
-
- daysRetentionSqlite := defaultRetentionDays
- sqliteRetentionDays := strings.TrimSpace(cfg.SQLiteRetentionDays)
- if sqliteRetentionDays != "" {
- sqliteRetentionDaysInt, err := strconv.Atoi(sqliteRetentionDays)
- if err == nil && sqliteRetentionDaysInt >= 0 {
- daysRetentionSqlite = sqliteRetentionDaysInt
- }
- }
- startSQLiteRetention(ctx, daysRetentionSqlite)
- startRecordingDiskCleanup(ctx, daysRetentionRecordings)
+ startSQLiteRetention(ctx, parseRetentionDays(cfg.SQLiteRetentionDays))
+ startRecordingDiskCleanup(ctx, parseRetentionDays(cfg.SessionRecordingRetentionDays))
+ startProfileArchiveDiskCleanup(ctx, parseRetentionDays(cfg.ProfileRetentionDays))
startOAuthSessionsPrune(ctx)
}
+
+func parseRetentionDays(value string) int {
+ trimmed := strings.TrimSpace(value)
+ if trimmed == "" {
+ return defaultRetentionDays
+ }
+ days, err := strconv.Atoi(trimmed)
+ if err != nil || days < 0 {
+ return defaultRetentionDays
+ }
+ return days
+}
diff --git a/backend/app/retention/sqlite.go b/backend/app/retention/sqlite.go
index 5bfcbee1..cf5d6bdc 100644
--- a/backend/app/retention/sqlite.go
+++ b/backend/app/retention/sqlite.go
@@ -25,6 +25,9 @@ var telemetryRetentionTargets = []struct {
{"ai_traces", "recorded_at"},
{"log_records", "timestamp"},
{"sessions", "started_at"},
+ {"profiling_samples", "start_time"},
+ {"profiles", "recorded_at"},
+ {"profiling_stacks", "last_seen"},
}
func startSQLiteRetention(ctx context.Context, days int) {
diff --git a/backend/app/retention/sqlite_test.go b/backend/app/retention/sqlite_test.go
index 148a083e..7e761e40 100644
--- a/backend/app/retention/sqlite_test.go
+++ b/backend/app/retention/sqlite_test.go
@@ -130,6 +130,43 @@ func TestRunSQLiteRetention_AlreadyCancelledContextIsNoOp(t *testing.T) {
assertCount(t, db.TelemetryDB, "endpoints", 1)
}
+func TestRunSQLiteRetention_PrunesProfilingTables(t *testing.T) {
+ setupRetentionTestDB(t)
+
+ profilingTables := []struct {
+ table string
+ column string
+ }{
+ {"profiling_samples", "start_time"},
+ {"profiles", "recorded_at"},
+ {"profiling_stacks", "last_seen"},
+ }
+ for _, pt := range profilingTables {
+ ddl := fmt.Sprintf(
+ "CREATE TABLE IF NOT EXISTS %s (id TEXT, project_id TEXT, %s DATETIME NOT NULL)",
+ pt.table, pt.column,
+ )
+ if _, err := db.TelemetryDB.Exec(ddl); err != nil {
+ t.Fatalf("create %s: %v", pt.table, err)
+ }
+ }
+
+ now := time.Now().UTC()
+ old := now.AddDate(0, 0, -45)
+ fresh := now.AddDate(0, 0, -5)
+
+ for _, pt := range profilingTables {
+ insertWithTime(t, db.TelemetryDB, pt.table, pt.column, old)
+ insertWithTime(t, db.TelemetryDB, pt.table, pt.column, fresh)
+ }
+
+ runSQLiteRetention(context.Background(), 30)
+
+ for _, pt := range profilingTables {
+ assertCount(t, db.TelemetryDB, pt.table, 1)
+ }
+}
+
func assertCount(t *testing.T, ex *sql.DB, table string, want int) {
t.Helper()
if got := countRows(t, ex, table); got != want {