Expose storage usage and safe persisted age or size retention

This commit is contained in:
2026-11-06 21:34:55 +00:00
parent aa19c82156
commit 6abc309009
19 changed files with 1309 additions and 12 deletions
+15 -3
View File
@@ -2,6 +2,7 @@ package server
import (
"context"
"fmt"
"log"
"time"
@@ -103,8 +104,19 @@ func (r *runner) finishedSize(id int64) int64 {
// then tells every subscribed client which runs are gone. It holds r.mu so a run
// cannot become active between the executing check and the delete.
func (r *runner) deleteRuns(ids []int64) (*protocol.RunsDeletedResult, error) {
r.mu.Lock()
result, err := r.store.DeleteRuns(r.ctx, ids, r.artifactsRoot, func(id int64) string {
return r.deleteRunsContext(r.ctx, ids, false)
}
// Storage maintenance uses its own deadline and never queues behind execution.
func (r *runner) deleteRunsContext(ctx context.Context, ids []int64, try bool) (*protocol.RunsDeletedResult, error) {
if try {
if !r.mu.TryLock() {
return nil, fmt.Errorf("run maintenance is busy; retry shortly")
}
} else {
r.mu.Lock()
}
result, err := r.store.DeleteRuns(ctx, ids, r.artifactsRoot, func(id int64) string {
if _, ok := r.active[id]; ok {
return "run is executing"
}
@@ -126,7 +138,7 @@ func (r *runner) deleteRuns(ids []int64) (*protocol.RunsDeletedResult, error) {
r.notifyMu.Unlock()
// A deleted run's notifications are gone on every device.
if r.notes != nil {
c, cancel := context.WithTimeout(r.ctx, 5*time.Second)
c, cancel := context.WithTimeout(ctx, 5*time.Second)
r.notes.clearFor(c, pipeline.AppNotificationFilter{RunID: id})
cancel()
}
+6
View File
@@ -313,6 +313,12 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
return nil, err
}
}
// Storage maintenance may have removed a clean inactive tree while an
// admission was generating its title. Refuse that vanished workspace under
// the same lock used by removal instead of launching into a missing tree.
if info, err := os.Stat(workspace); err != nil || !info.IsDir() {
return nil, fmt.Errorf("run workspace is no longer available: %s", workspace)
}
id, created, err := r.store.CreateRunTitled(r.ctx, d, request.RequestKey, workspace, request.AllowTools, request.WritePaths, request.Input, pipeline.RunOverrides{Schedule: origin, Model: request.Model, StageModels: request.StageModels, NotifyMode: request.NotifyMode, OutputFormat: request.OutputFormat}, runTitle, retryOf...)
if err != nil {
return nil, err
+202
View File
@@ -0,0 +1,202 @@
package server
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"log"
"path/filepath"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
const storageInterval = time.Hour
const storagePreviewLifetime = 10 * time.Minute
type storagePreview struct {
result protocol.StorageCleanupResult
expires time.Time
}
type storageManager struct {
scan func(context.Context, storageInventoryConfig) (storageInventory, error)
worker chan struct{}
roots *storageInventoryConfig
workspaceMu sync.RWMutex
mu sync.Mutex
runner *runner
store *pipeline.Store
previews map[string]storagePreview
}
func newStorageManager(r *runner) *storageManager {
return &storageManager{runner: r, store: r.store, previews: map[string]storagePreview{}, worker: make(chan struct{}, 1)}
}
// dispatch bounds slow storage work to one goroutine without blocking the
// shared socket read loop. The transport's write callback serializes replies.
func (m *storageManager) dispatch(ctx context.Context, request protocol.Message, write func(protocol.Message) error) {
select {
case m.worker <- struct{}{}:
go func() { defer func() { <-m.worker }(); _ = write(m.handle(ctx, request)) }()
default:
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "storage management is busy; retry shortly"})
}
}
func isStorageRequest(t string) bool {
return t == protocol.GetStorage || t == protocol.SetStoragePolicy || t == protocol.PreviewStorageCleanup || t == protocol.ApplyStorageCleanup
}
func (m *storageManager) handle(ctx context.Context, request protocol.Message) protocol.Message {
if !m.mu.TryLock() {
return protocol.Message{Type: protocol.Error, ID: request.ID, Error: "storage management is busy; retry shortly"}
}
defer m.mu.Unlock()
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
response := protocol.Message{ID: request.ID}
var err error
switch request.Type {
case protocol.GetStorage:
response.Type = protocol.StorageReply
response.Storage, err = m.overview(ctx)
case protocol.SetStoragePolicy:
response.Type = protocol.StoragePolicySaved
if request.StoragePolicy == nil {
err = fmt.Errorf("storage_policy is required")
break
}
err = m.store.SaveStoragePolicy(ctx, *request.StoragePolicy)
if err == nil {
response.Storage, err = m.overview(ctx)
}
case protocol.PreviewStorageCleanup:
response.Type = protocol.StorageCleanupPreview
var policy protocol.StoragePolicy
policy, err = m.policy(ctx, request.StoragePolicy)
if err == nil {
response.StorageCleanup, err = m.preview(ctx, policy)
if err == nil {
response.StorageCleanup.PreviewToken = m.remember(*response.StorageCleanup)
}
}
case protocol.ApplyStorageCleanup:
response.Type = protocol.StorageCleanupApplied
var saved storagePreview
saved, err = m.consume(request.StorageCleanupToken, request.StoragePolicy)
if err == nil {
response.StorageCleanup, err = m.apply(ctx, saved.result)
}
}
if err != nil {
response.Type = protocol.Error
response.Error = err.Error()
}
return response
}
func (m *storageManager) policy(ctx context.Context, supplied *protocol.StoragePolicy) (protocol.StoragePolicy, error) {
if supplied != nil {
return *supplied, supplied.Validate()
}
return m.store.StoragePolicy(ctx)
}
func (m *storageManager) remember(result protocol.StorageCleanupResult) string {
for token, p := range m.previews {
if time.Now().After(p.expires) {
delete(m.previews, token)
}
}
// A preview is small and short lived; bound clients repeatedly requesting it.
if len(m.previews) >= 32 {
for token := range m.previews {
delete(m.previews, token)
break
}
}
var key [24]byte
if _, err := rand.Read(key[:]); err != nil {
return ""
}
token := hex.EncodeToString(key[:])
m.previews[token] = storagePreview{result: result, expires: time.Now().Add(storagePreviewLifetime)}
return token
}
func (m *storageManager) consume(token string, policy *protocol.StoragePolicy) (storagePreview, error) {
p, ok := m.previews[token]
if !ok || time.Now().After(p.expires) {
return p, fmt.Errorf("cleanup preview expired; preview cleanup again")
}
if policy == nil || *policy != p.result.Policy {
return p, fmt.Errorf("retention policy changed; preview cleanup again")
}
delete(m.previews, token)
return p, nil
}
func (m *storageManager) overview(ctx context.Context) (*protocol.StorageOverview, error) {
policy, err := m.store.StoragePolicy(ctx)
if err != nil {
return nil, err
}
inventory, err := m.inventory(ctx)
if err != nil {
return nil, err
}
result := &protocol.StorageOverview{Measurement: "logical_file_bytes", TotalBytes: inventory.TotalBytes, Policy: policy, MeasuredAt: time.Now().UTC().Format(time.RFC3339), Partial: inventory.Partial, Warnings: inventory.Errors, AutomaticIntervalSeconds: int(storageInterval / time.Second), Categories: []protocol.StorageCategory{}}
for _, c := range inventory.Categories {
result.Categories = append(result.Categories, protocol.StorageCategory{ID: c.ID, Label: c.Label, Path: c.Path, Bytes: c.Bytes, Files: c.Files, Partial: c.Partial, Error: c.Error})
}
return result, nil
}
func storageTerminal(status string) bool {
switch status {
case "succeeded", "failed", "canceled", "interrupted":
return true
}
return false
}
func (m *storageManager) loop(ctx context.Context) {
defer m.runner.schedulerWG.Done()
ticker := time.NewTicker(storageInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-m.store.Done():
return
case <-ticker.C:
if !m.mu.TryLock() {
continue
}
cycle, cancel := context.WithTimeout(ctx, 20*time.Second)
err := m.automaticPass(cycle)
cancel()
m.mu.Unlock()
if err != nil && ctx.Err() == nil {
log.Printf("storage retention: %v", err)
}
}
}
}
// canonicalStoragePath supplies the consistent key used by preview identities.
func canonicalStoragePath(path string) string { return filepath.Clean(path) }
// automaticPass is invoked only by the hourly tick, never at startup or save.
func (m *storageManager) automaticPass(ctx context.Context) error {
policy, err := m.store.StoragePolicy(ctx)
if err != nil || !policy.Enabled {
return err
}
preview, err := m.preview(ctx, policy)
if err != nil || preview.CandidateCount == 0 {
return err
}
result, err := m.apply(ctx, *preview)
if err == nil && len(result.Errors) > 0 {
return fmt.Errorf("retention incomplete: %s", result.Errors[0])
}
return err
}
+239
View File
@@ -0,0 +1,239 @@
package server
import (
"context"
"fmt"
"path/filepath"
"sort"
"strconv"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
type storageCandidate struct {
item protocol.StorageCleanupItem
timestamp time.Time
}
func (m *storageManager) preview(ctx context.Context, policy protocol.StoragePolicy) (*protocol.StorageCleanupResult, error) {
if err := policy.Validate(); err != nil {
return nil, err
}
inventory, err := m.inventory(ctx)
if err != nil {
return nil, err
}
result := &protocol.StorageCleanupResult{Policy: policy, TotalBytes: inventory.TotalBytes, TargetBytes: policy.MaxBytes, Items: []protocol.StorageCleanupItem{}, Errors: append([]string{}, inventory.Errors...)}
runs, err := m.store.ListRuns(ctx)
if err != nil {
return nil, err
}
recordProtected := func(item protocol.StorageCleanupItem) {
result.ProtectedCount++
if result.ProtectedCount <= 200 {
result.Items = append(result.Items, item)
}
if result.ProtectedCount == 201 {
result.Errors = append(result.Errors, "Only the first 200 protected items are shown; the protected count includes all items.")
}
}
var candidates []storageCandidate
artifactWalker := storageWalker{ctx: ctx, seen: map[string]bool{}, inodes: map[[2]uint64]bool{}}
for _, run := range runs {
if err := ctx.Err(); err != nil {
return nil, err
}
_, reason, err := m.store.PreviewRunDeletion(ctx, run.ID, m.runner.artifactsRoot)
if err != nil {
return nil, err
}
item := protocol.StorageCleanupItem{Kind: "run", ID: strconv.FormatInt(run.ID, 10), Path: filepath.Join(m.runner.artifactsRoot, strconv.FormatInt(run.ID, 10)), Protected: reason != "", Reason: reason}
if reason != "" {
recordProtected(item)
continue
}
measured := storageCategory{}
artifactWalker.measure(item.Path, &measured)
bytes, partial := measured.Bytes, measured.Partial
var problems []string
if measured.Error != "" {
problems = append(problems, measured.Error)
}
if partial {
item.Protected = true
item.Reason = "artifact measurement incomplete"
recordProtected(item)
result.Errors = append(result.Errors, problems...)
continue
}
item.Bytes = bytes
stamp := run.FinishedAt
if stamp == "" {
stamp = run.CreatedAt
}
candidates = append(candidates, storageCandidate{item: item, timestamp: storageTime(stamp)})
}
if policy.IncludeWorktrees {
for _, tree := range inventory.Worktrees {
item := protocol.StorageCleanupItem{Kind: "worktree", ID: canonicalStoragePath(tree.Path), Path: tree.Path, Bytes: tree.Bytes, Protected: !tree.Eligible, Reason: tree.Reason}
if !tree.Eligible {
recordProtected(item)
continue
}
candidates = append(candidates, storageCandidate{item: item, timestamp: tree.ModifiedAt})
}
}
sort.Slice(candidates, func(i, j int) bool { return candidates[i].timestamp.Before(candidates[j].timestamp) })
remaining := inventory.TotalBytes
cutoff := time.Now().Add(-time.Duration(policy.MaxAgeDays) * 24 * time.Hour)
for _, candidate := range candidates {
expired := policy.MaxAgeDays > 0 && !candidate.timestamp.IsZero() && candidate.timestamp.Before(cutoff)
over := policy.MaxBytes > 0 && remaining > policy.MaxBytes
if !expired && !over {
continue
}
if result.CandidateCount >= 100 {
result.Errors = append(result.Errors, "Cleanup is limited to 100 items per pass; preview again for remaining items.")
break
}
item := candidate.item
if expired {
item.Reason = "older than retention age"
} else {
item.Reason = "oldest eligible data above storage target"
}
result.Items = append(result.Items, item)
result.CandidateCount++
result.ReclaimableBytes += item.Bytes
remaining = max(int64(0), remaining-item.Bytes)
}
result.TargetReached = policy.MaxBytes == 0 || remaining <= policy.MaxBytes
if inventory.Partial {
result.Errors = append(result.Errors, "Storage measurement is partial; the total and target result are lower bounds.")
result.TargetReached = false
}
return result, nil
}
func storageTime(value string) time.Time {
for _, layout := range []string{time.RFC3339Nano, "2006-01-02 15:04:05"} {
if t, err := time.Parse(layout, value); err == nil {
return t
}
}
return time.Time{}
}
func (m *storageManager) apply(ctx context.Context, preview protocol.StorageCleanupResult) (*protocol.StorageCleanupResult, error) {
result := preview
result.PreviewToken = ""
result.Applied = true
before, err := m.inventory(ctx)
if err != nil {
return nil, err
}
var ids []int64
for _, item := range preview.Items {
if item.Protected || item.Kind != "run" {
continue
}
id, err := strconv.ParseInt(item.ID, 10, 64)
if err != nil {
return nil, err
}
ids = append(ids, id)
}
if len(ids) > 0 {
deleted, err := m.runner.deleteRunsContext(ctx, ids, true)
if err != nil {
return nil, err
}
result.RemovedCount += len(deleted.Deleted)
removed := map[string]bool{}
for _, id := range deleted.Deleted {
removed[strconv.FormatInt(id, 10)] = true
}
for _, item := range preview.Items {
if item.Kind == "run" && removed[item.ID] {
result.RemovedBytes += item.Bytes
}
}
result.RemovedBytes = max(int64(0), result.RemovedBytes-deleted.RemainingFileBytes)
if deleted.RemainingFileBytes > 0 {
result.Errors = append(result.Errors, "Some staged files remain after run deletion; their bytes are not counted as removed.")
}
for _, refused := range deleted.Refused {
result.Errors = append(result.Errors, fmt.Sprintf("Run %d retained: %s", refused.RunID, refused.Reason))
}
}
for _, item := range preview.Items {
if item.Protected || item.Kind != "worktree" {
continue
}
if err := ctx.Err(); err != nil {
result.Errors = append(result.Errors, err.Error())
break
}
// Admission and removal are serialized against the runner. Chat creation
// takes the workspace gate in the websocket dispatcher before recording paths.
if !m.workspaceMu.TryLock() {
result.Errors = append(result.Errors, "Worktree retained: chat workspace admission is busy")
continue
}
if !m.runner.mu.TryLock() {
m.workspaceMu.Unlock()
result.Errors = append(result.Errors, "Worktree retained: run workspace admission is busy")
continue
}
removalCtx, cancelRemoval := context.WithTimeout(ctx, 3*time.Second)
config, err := m.inventoryConfig(removalCtx)
if err == nil {
for _, active := range m.runner.active {
config.ProtectedWorkspaces = append(config.ProtectedWorkspaces, active.workspace)
}
var tree storageWorktree
found := false
for _, known := range before.Worktrees {
if canonicalStoragePath(known.Path) == canonicalStoragePath(item.Path) {
tree = known
found = true
break
}
}
if !found {
err = fmt.Errorf("worktree is no longer inventoried")
} else {
err = removeStorageWorktree(removalCtx, tree, config.ProtectedWorkspaces)
}
}
cancelRemoval()
m.runner.mu.Unlock()
m.workspaceMu.Unlock()
if err != nil {
result.Errors = append(result.Errors, fmt.Sprintf("Worktree %s retained: %v", item.Path, err))
} else {
result.RemovedCount++
result.RemovedBytes += treeBytes(before.Worktrees, item.Path)
}
}
after, err := m.inventory(ctx)
if err != nil {
result.Errors = append(result.Errors, err.Error())
result.TargetReached = false
return &result, nil
}
result.TotalBytes = after.TotalBytes
// Sum only successfully removed measured file attribution. A partial
// post-scan or concurrent writes must never fabricate a reclaimed total.
result.TargetReached = !after.Partial && (result.Policy.MaxBytes == 0 || after.TotalBytes <= result.Policy.MaxBytes)
result.Errors = append(result.Errors, after.Errors...)
return &result, nil
}
func treeBytes(trees []storageWorktree, path string) int64 {
for _, tree := range trees {
if canonicalStoragePath(tree.Path) == canonicalStoragePath(path) {
return tree.Bytes
}
}
return 0
}
+53
View File
@@ -0,0 +1,53 @@
package server
import (
"context"
"git.a-wan.net/alan/pipelines/internal/protocol"
"testing"
"time"
)
func TestStoragePartialMeasurementSurvivesBudgetExpiry(t *testing.T) {
f := newStorageFixture(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
f.m.scan = func(context.Context, storageInventoryConfig) (storageInventory, error) {
cancel()
return storageInventory{TotalBytes: 123, Partial: true, Categories: []storageCategory{{ID: "worktrees", Bytes: 123, Partial: true}}, Worktrees: []storageWorktree{{Path: f.workspace, Repository: f.workspace}}, Errors: []string{"measurement budget expired"}}, nil
}
got, err := f.m.overview(ctx)
if err != nil || got == nil || !got.Partial || got.TotalBytes != 123 {
t.Fatalf("partial %+v %v", got, err)
}
}
func TestStoragePartialPostScanCannotInventRemovedBytes(t *testing.T) {
f := newStorageFixture(t)
old := time.Now().Add(-40 * 24 * time.Hour)
id := f.run(t, "partial-postscan", "succeeded", old, old)
policy := protocol.StoragePolicy{MaxAgeDays: 7}
preview, err := f.m.preview(context.Background(), policy)
if err != nil {
t.Fatal(err)
}
if preview.CandidateCount != 1 {
t.Fatalf("preview %+v", preview)
}
scans := 0
f.m.scan = func(ctx context.Context, c storageInventoryConfig) (storageInventory, error) {
scans++
if scans == 1 {
return storageInventory{TotalBytes: 1 << 40}, nil
}
return storageInventory{Partial: true, TotalBytes: 0, Errors: []string{"partial after scan"}}, nil
}
result, err := f.m.apply(context.Background(), *preview)
if err != nil {
t.Fatal(err)
}
if result.RemovedCount != 1 || result.RemovedBytes != 4096 || result.TargetReached {
t.Fatalf("partial reclaim %+v", result)
}
if _, err := f.m.store.GetRun(context.Background(), id); err == nil {
t.Fatal("run was not removed")
}
}
+93
View File
@@ -0,0 +1,93 @@
package server
import (
"context"
"os"
"path/filepath"
)
func (m *storageManager) inventory(ctx context.Context) (storageInventory, error) {
config, err := m.inventoryConfig(ctx)
if err != nil {
return storageInventory{}, err
}
scan := m.scan
if scan == nil {
scan = inspectStorage
}
inventory, err := scan(ctx, config)
if err != nil {
return inventory, err
}
// Keep discovered repository identities after deleting the last referencing
// run/worktree; otherwise the next total could silently lose sibling trees.
var observed []string
for _, tree := range inventory.Worktrees {
observed = append(observed, tree.Path, tree.Repository)
}
if len(observed) > 0 && ctx.Err() == nil {
if err := m.store.RememberStorageWorkspaces(ctx, observed); err != nil {
return inventory, err
}
}
return inventory, nil
}
func (m *storageManager) inventoryConfig(ctx context.Context) (storageInventoryConfig, error) {
config := storageInventoryConfig{DataRoot: m.store.Directory(), ArtifactsRoot: m.runner.artifactsRoot}
// The database path is obtained from the store, never supplied by a client.
config.DatabasePath = m.store.DatabasePath()
var err error
if m.roots != nil {
config = *m.roots
config.DatabasePath = m.store.DatabasePath()
config.DataRoot = m.store.Directory()
} else {
cache, cacheErr := os.UserCacheDir()
if cacheErr != nil {
return config, cacheErr
}
config.SessionsRoot = filepath.Join(cache, "pipelines", "pi-sessions")
config.AttachmentsRoot, err = chatAttachmentDir()
if err != nil {
return config, err
}
}
config.ProtectedWorkspaces = append(config.ProtectedWorkspaces, config.DataRoot, config.ArtifactsRoot, config.AttachmentsRoot, config.SessionsRoot)
runs, err := m.store.ListRuns(ctx)
if err != nil {
return config, err
}
for _, run := range runs {
config.WorkspaceRoots = append(config.WorkspaceRoots, run.Workspace)
if !storageTerminal(run.Status) || run.CleanupUnconfirmed {
config.ProtectedWorkspaces = append(config.ProtectedWorkspaces, run.Workspace)
}
}
directories, err := m.store.StorageOperatorDirectories(ctx)
if err != nil {
return config, err
}
config.WorkspaceRoots = append(config.WorkspaceRoots, directories...)
config.ProtectedWorkspaces = append(config.ProtectedWorkspaces, directories...)
if err := m.store.RememberStorageWorkspaces(ctx, config.WorkspaceRoots); err != nil {
return config, err
}
remembered, err := m.store.StorageWorkspacePaths(ctx)
if err != nil {
return config, err
}
config.WorkspaceRoots = append(config.WorkspaceRoots, remembered...)
seen := map[string]bool{}
unique := config.WorkspaceRoots[:0]
for _, path := range config.WorkspaceRoots {
if path != "" {
path = filepath.Clean(path)
if !seen[path] {
unique = append(unique, path)
seen[path] = true
}
}
}
config.WorkspaceRoots = unique
return config, nil
}
+242
View File
@@ -0,0 +1,242 @@
package server
import (
"context"
"database/sql"
"fmt"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
type storageFixture struct {
m *storageManager
definition *protocol.PipelineDetail
workspace string
}
func newStorageFixture(t *testing.T) storageFixture {
t.Helper()
ctx := context.Background()
root := t.TempDir()
store, err := pipeline.Open(filepath.Join(root, "data", "storage.db"))
if err != nil {
if err := os.MkdirAll(filepath.Join(root, "data"), 0700); err != nil {
t.Fatal(err)
}
store, err = pipeline.Open(filepath.Join(root, "data", "storage.db"))
if err != nil {
t.Fatal(err)
}
}
t.Cleanup(func() { store.Close() })
if _, err := store.Submit(ctx, "storage-fixture", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
list, err := store.List(ctx)
if err != nil {
t.Fatal(err)
}
d, err := store.Get(ctx, list[0].ID, 1)
if err != nil {
t.Fatal(err)
}
r := &runner{ctx: ctx, store: store, artifactsRoot: filepath.Join(root, "artifacts"), active: map[int64]activeRun{}}
m := newStorageManager(r)
m.roots = &storageInventoryConfig{AttachmentsRoot: filepath.Join(root, "attachments"), SessionsRoot: filepath.Join(root, "sessions")}
workspace := filepath.Join(root, "workspace")
if err := os.MkdirAll(workspace, 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(workspace, "source.txt"), []byte("source is preserved"), 0600); err != nil {
t.Fatal(err)
}
return storageFixture{m, d, workspace}
}
func (f storageFixture) run(t *testing.T, key, status string, created, finished time.Time) int64 {
t.Helper()
ctx := context.Background()
id, _, err := f.m.store.CreateRun(ctx, f.definition, key, f.workspace, false, nil, map[string]any{"prompt": "fixture"})
if err != nil {
t.Fatal(err)
}
if storageTerminal(status) {
if err := f.m.store.FinishRun(ctx, id, status, "success", "", nil); err != nil {
t.Fatal(err)
}
}
db, err := sql.Open("sqlite", f.m.store.DatabasePath())
if err != nil {
t.Fatal(err)
}
defer db.Close()
if _, err := db.Exec(`UPDATE pipeline_runs SET created_at=?,finished_at=? WHERE id=?`, created.UTC().Format(time.RFC3339), finished.UTC().Format(time.RFC3339), id); err != nil {
t.Fatal(err)
}
path := filepath.Join(f.m.runner.artifactsRoot, strconv.FormatInt(id, 10))
if err := os.MkdirAll(path, 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(path, "report.txt"), make([]byte, 4096), 0600); err != nil {
t.Fatal(err)
}
return id
}
func TestStorageRetentionPreviewBoundApplyAndCompletionAge(t *testing.T) {
f := newStorageFixture(t)
now := time.Now()
old := now.Add(-40 * 24 * time.Hour)
expired := f.run(t, "old", "succeeded", old, old)
recent := f.run(t, "long-but-recent", "succeeded", old, now)
active := f.run(t, "active", "running", old, old)
policy := protocol.StoragePolicy{MaxAgeDays: 7}
response := f.m.handle(context.Background(), protocol.Message{Type: protocol.PreviewStorageCleanup, StoragePolicy: &policy})
if response.Type != protocol.StorageCleanupPreview {
t.Fatalf("preview %+v", response)
}
p := response.StorageCleanup
if p.CandidateCount != 1 || p.ProtectedCount != 1 || p.ReclaimableBytes != 4096 || p.PreviewToken == "" {
t.Fatalf("preview %+v", p)
}
// A new eligible run that appears after confirmation is never added to apply.
newerCandidate := f.run(t, "new-candidate", "succeeded", old, old)
applied := f.m.handle(context.Background(), protocol.Message{Type: protocol.ApplyStorageCleanup, StoragePolicy: &policy, StorageCleanupToken: p.PreviewToken})
if applied.Type != protocol.StorageCleanupApplied || applied.StorageCleanup.RemovedCount != 1 {
t.Fatalf("apply %+v", applied)
}
runs, err := f.m.store.ListRuns(context.Background())
if err != nil {
t.Fatal(err)
}
seen := map[int64]bool{}
for _, r := range runs {
seen[r.ID] = true
}
if seen[expired] || !seen[recent] || !seen[active] || !seen[newerCandidate] {
t.Fatalf("remaining %+v", seen)
}
if _, err := os.Stat(filepath.Join(f.workspace, "source.txt")); err != nil {
t.Fatal("workspace was removed")
}
// Remembered roots retain total inventory coverage after their last run goes.
paths, err := f.m.store.StorageWorkspacePaths(context.Background())
if err != nil || len(paths) == 0 {
t.Fatalf("roots %v %v", paths, err)
}
again := f.m.handle(context.Background(), protocol.Message{Type: protocol.ApplyStorageCleanup, StoragePolicy: &policy, StorageCleanupToken: p.PreviewToken})
if again.Type != protocol.Error {
t.Fatal("preview token reused")
}
}
func TestStorageTokensPolicyValidationAndSizeTarget(t *testing.T) {
f := newStorageFixture(t)
old := time.Now().Add(-40 * 24 * time.Hour)
f.run(t, "old", "succeeded", old, old)
policy := protocol.StoragePolicy{MaxBytes: 1}
response := f.m.handle(context.Background(), protocol.Message{Type: protocol.PreviewStorageCleanup, StoragePolicy: &policy})
p := response.StorageCleanup
if p == nil || p.TargetReached || p.CandidateCount != 1 {
t.Fatalf("size preview %+v", response)
}
changed := policy
changed.MaxBytes = 2
if got := f.m.handle(context.Background(), protocol.Message{Type: protocol.ApplyStorageCleanup, StoragePolicy: &changed, StorageCleanupToken: p.PreviewToken}); got.Type != protocol.Error {
t.Fatal("changed policy accepted")
}
saved := f.m.previews[p.PreviewToken]
saved.expires = time.Now().Add(-time.Second)
f.m.previews[p.PreviewToken] = saved
if got := f.m.handle(context.Background(), protocol.Message{Type: protocol.ApplyStorageCleanup, StoragePolicy: &policy, StorageCleanupToken: p.PreviewToken}); got.Type != protocol.Error {
t.Fatal("expired token accepted")
}
bad := protocol.StoragePolicy{Enabled: true}
if got := f.m.handle(context.Background(), protocol.Message{Type: protocol.SetStoragePolicy, StoragePolicy: &bad}); got.Type != protocol.Error {
t.Fatal("invalid automatic policy accepted")
}
overview := f.m.handle(context.Background(), protocol.Message{Type: protocol.GetStorage})
if overview.Storage == nil || overview.Storage.Policy.Enabled || overview.Storage.Measurement != "logical_file_bytes" {
t.Fatalf("overview %+v", overview)
}
}
func TestStorageBusyDispatchDoesNotWaitForMaintenance(t *testing.T) {
f := newStorageFixture(t)
f.m.mu.Lock()
replies := make(chan protocol.Message, 1)
f.m.dispatch(context.Background(), protocol.Message{Type: protocol.GetStorage, ID: "busy"}, func(m protocol.Message) error { replies <- m; return nil })
select {
case reply := <-replies:
if reply.Type != protocol.Error {
t.Fatalf("reply %+v", reply)
}
case <-time.After(time.Second):
t.Fatal("busy storage request blocked")
}
f.m.mu.Unlock()
}
func TestStorageWebsocketProtocolAndNoStartupCleanup(t *testing.T) {
// Isolate attachment and harness cache roots; this test never inventories the
// operator's real home, chats or repositories.
t.Setenv("HOME", t.TempDir())
t.Setenv("PIPELINES_CHAT_ATTACHMENT_DIR", t.TempDir())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
f := newStorageFixture(t)
old := time.Now().Add(-40 * 24 * time.Hour)
id := f.run(t, "old", "succeeded", old, old)
policy := protocol.StoragePolicy{Enabled: true, MaxAgeDays: 7}
if err := f.m.store.SaveStoragePolicy(ctx, policy); err != nil {
t.Fatal(err)
}
handler := HandlerWithOptions(ctx, Options{ArtifactsRoot: f.m.runner.artifactsRoot}, f.m.store)
defer func() { cancel(); WaitRuns(handler) }()
srv := httptest.NewServer(handler)
defer srv.Close()
conn := dialAckClient(t, ctx, srv.URL)
reply := ackExchange(t, ctx, conn, protocol.Message{Type: protocol.GetStorage, ID: "storage"})
if reply.Type != protocol.StorageReply || reply.ID != "storage" || reply.Storage == nil || !reply.Storage.Policy.Enabled {
t.Fatalf("wire %+v", reply)
}
if _, err := f.m.store.GetRun(ctx, id); err != nil {
t.Fatal("startup pruned run", err)
}
invalid := ackExchange(t, ctx, conn, protocol.Message{Type: protocol.SetStoragePolicy, ID: "invalid"})
if invalid.Type != protocol.Error {
t.Fatalf("invalid %+v", invalid)
}
ping := ackExchange(t, ctx, conn, protocol.Message{Type: protocol.Ping, ID: "ping"})
if ping.Type != protocol.Pong {
t.Fatal(fmt.Sprint(ping))
}
}
func TestStorageAutomaticPolicyOptInAndActiveProtection(t *testing.T) {
f := newStorageFixture(t)
ctx := context.Background()
old := time.Now().Add(-40 * 24 * time.Hour)
expired := f.run(t, "automatic-old", "succeeded", old, old)
active := f.run(t, "automatic-active", "running", old, old)
if err := f.m.automaticPass(ctx); err != nil {
t.Fatal(err)
}
if _, err := f.m.store.GetRun(ctx, expired); err != nil {
t.Fatal("disabled automatic policy deleted history")
}
if err := f.m.store.SaveStoragePolicy(ctx, protocol.StoragePolicy{Enabled: true, MaxAgeDays: 7}); err != nil {
t.Fatal(err)
}
if err := f.m.automaticPass(ctx); err != nil {
t.Fatal(err)
}
if _, err := f.m.store.GetRun(ctx, expired); err == nil {
t.Fatal("enabled policy did not remove expired run")
}
if _, err := f.m.store.GetRun(ctx, active); err != nil {
t.Fatal("active run removed", err)
}
}
+27 -1
View File
@@ -107,6 +107,12 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
go runs.sizeLoop()
}
}
var storage *storageManager
if runs != nil {
storage = newStorageManager(runs)
runs.schedulerWG.Add(1)
go storage.loop(ctx)
}
// chat_sessions lists the operator's own recorded sessions. Prefer an
// injected registry; otherwise derive it from the store. With neither, the
// handler fails closed to an empty list.
@@ -244,7 +250,27 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
}(request)
continue
}
if handleChat(connCtx, request, options.Chat, hub, registry, clientID, write) {
// Prevent a new operator workspace admission racing a worktree
// removal. Ordinary reads/prompts do not wait for storage scans.
admission := storage != nil && (request.Type == protocol.ChatCreate || request.Type == protocol.ChatAdopt)
if admission {
storage.workspaceMu.RLock()
}
handledChat := handleChat(connCtx, request, options.Chat, hub, registry, clientID, write)
if admission {
storage.workspaceMu.RUnlock()
}
if handledChat {
continue
}
if isStorageRequest(request.Type) {
if storage == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "storage management unavailable: no execution store"})
} else {
// Disk/Git inventory must never stall chat permissions/prompts
// arriving on this same persistent connection.
storage.dispatch(connCtx, request, write)
}
continue
}
if handleDirectoryListing(request, write) {