Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions cmd/fanout/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,10 +303,10 @@ func main() {
// typed query kernel through deterministic HTTP or standard MCP tools.
// Route both HTTP and MCP reads through Duck's retrying adapter. Passing the
// raw *sql.DB here bypassed the Telemetry maintenance-race protection.
queries := observability.New(q, q)
queries := observability.New(q, q, cfg.RetentionDays)
api.NewObservabilityHandler(queries).Register(e.Group("/api/observability", api.RequireCapability(api.ReadTelemetry)))
api.RegisterIntelligenceRoutes(e, detector)
dashboards := dashboard.New(sqlite.DB)
dashboards := dashboard.New(sqlite.DB, cfg.RetentionDays)
api.RegisterDashboardRoutes(e, dashboards)

// Alert management REST endpoints
Expand Down
4 changes: 2 additions & 2 deletions internal/api/dashboard_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func TestAnonymousCannotOwnDashboards(t *testing.T) {
if _, err := s.users.Create("admin@example.com", "", "admin"); err != nil {
t.Fatalf("Create admin: %v", err)
}
RegisterDashboardRoutes(s.e, dashboard.New(s.db.DB))
RegisterDashboardRoutes(s.e, dashboard.New(s.db.DB, 30))
rec := httptest.NewRecorder()
s.e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/dashboards", nil))
if rec.Code != http.StatusUnauthorized {
Expand All @@ -31,7 +31,7 @@ func TestDashboardRoutesHideOtherOwnersResources(t *testing.T) {
if err != nil {
t.Fatalf("Create owner B: %v", err)
}
dashboards := dashboard.New(s.db.DB)
dashboards := dashboard.New(s.db.DB, 30)
item, err := dashboards.Default(t.Context(), ownerA.ID)
if err != nil {
t.Fatalf("create dashboard: %v", err)
Expand Down
53 changes: 30 additions & 23 deletions internal/api/observability_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,30 +46,37 @@ func (f *fakeQueries) Logs(_ context.Context, _ observability.Scope, _, _, _ str
}

func TestOverviewRouteUsesDurationScope(t *testing.T) {
queries := &fakeQueries{}
h := NewObservabilityHandler(queries)
h.now = func() time.Time { return time.Date(2026, 7, 20, 12, 0, 0, 0, time.UTC) }
e := echo.New()
h.Register(e.Group("/api/observability"))
for _, tt := range []struct {
window string
want time.Duration
}{{"15m", 15 * time.Minute}, {"720h", 30 * 24 * time.Hour}} {
t.Run(tt.window, func(t *testing.T) {
queries := &fakeQueries{}
h := NewObservabilityHandler(queries)
h.now = func() time.Time { return time.Date(2026, 7, 20, 12, 0, 0, 0, time.UTC) }
e := echo.New()
h.Register(e.Group("/api/observability"))

req := httptest.NewRequest(http.MethodGet, "/api/observability/overview?window=15m&namespace=prod", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String())
}
if got := queries.overviewScope.End.Sub(queries.overviewScope.Start); got != 15*time.Minute {
t.Fatalf("window = %s, want 15m", got)
}
if queries.overviewScope.Namespace != "prod" {
t.Fatalf("namespace = %q, want prod", queries.overviewScope.Namespace)
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("decode response: %v", err)
}
if body["schema"] != observability.OverviewSchema {
t.Fatalf("schema = %v", body["schema"])
req := httptest.NewRequest(http.MethodGet, "/api/observability/overview?window="+tt.window+"&namespace=prod", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String())
}
if got := queries.overviewScope.End.Sub(queries.overviewScope.Start); got != tt.want {
t.Fatalf("window = %s, want %s", got, tt.want)
}
if queries.overviewScope.Namespace != "prod" {
t.Fatalf("namespace = %q, want prod", queries.overviewScope.Namespace)
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("decode response: %v", err)
}
if body["schema"] != observability.OverviewSchema {
t.Fatalf("schema = %v", body["schema"])
}
})
}
}

Expand Down
52 changes: 48 additions & 4 deletions internal/dashboard/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,18 @@ type UpdateInput struct {
}

type Service struct {
db *sql.DB
now func() time.Time
db *sql.DB
maxWindow time.Duration
now func() time.Time
}

func New(db *sql.DB) *Service { return &Service{db: db, now: time.Now} }
func New(db *sql.DB, retentionDays int) *Service {
maxWindow := 30 * 24 * time.Hour
if retentionDays > 0 {
maxWindow = time.Duration(retentionDays) * 24 * time.Hour
}
return &Service{db: db, maxWindow: maxWindow, now: time.Now}
}

func DefaultState() State {
return State{
Expand Down Expand Up @@ -162,6 +169,7 @@ func (s *Service) Create(ctx context.Context, ownerID string, input CreateInput)
if err := Validate(input.Name, input.Description, input.State); err != nil {
return Dashboard{}, err
}
input.State.Filters.Window = clampDashboardWindow(input.State.Filters.Window, s.maxWindow)
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return Dashboard{}, err
Expand Down Expand Up @@ -204,6 +212,7 @@ func (s *Service) Update(ctx context.Context, ownerID, id string, input UpdateIn
if err := Validate(input.Name, input.Description, input.State); err != nil {
return Dashboard{}, err
}
input.State.Filters.Window = clampDashboardWindow(input.State.Filters.Window, s.maxWindow)
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return Dashboard{}, err
Expand Down Expand Up @@ -266,6 +275,7 @@ func (s *Service) get(ctx context.Context, q interface {
} else if err != nil {
return Dashboard{}, err
}
out.State.Filters.Window = clampDashboardWindow(out.State.Filters.Window, s.maxWindow)
rows, err := q.QueryContext(ctx, `SELECT id,type,title,config_json,enabled,x,y,w,h,min_w,min_h FROM dashboard_widgets WHERE dashboard_id=? ORDER BY sort_order,id`, id)
if err != nil {
return Dashboard{}, err
Expand Down Expand Up @@ -367,6 +377,18 @@ func (s *Service) ensureInitial(ctx context.Context, ownerID string) error {
// duplicating the literals.
var WidgetTypes = []string{"overview", "topology", "activity", "assistant", "performance", "trace", "logs"}

var dashboardWindows = []struct {
value string
duration time.Duration
}{
{"15m", 15 * time.Minute},
{"1h", time.Hour},
{"6h", 6 * time.Hour},
{"24h", 24 * time.Hour},
{"168h", 7 * 24 * time.Hour},
{"720h", 30 * 24 * time.Hour},
}

func Validate(name, description string, state State) error {
if len(strings.TrimSpace(name)) == 0 || len([]rune(strings.TrimSpace(name))) > 80 {
return invalid("dashboard name must be between 1 and 80 characters")
Expand Down Expand Up @@ -409,12 +431,34 @@ func Validate(name, description string, state State) error {
}
}
}
if state.Filters.Window != "15m" && state.Filters.Window != "1h" && state.Filters.Window != "6h" && state.Filters.Window != "24h" {
if _, ok := dashboardWindowDuration(state.Filters.Window); !ok {
return invalid("unsupported dashboard window")
}
return nil
}

func dashboardWindowDuration(value string) (time.Duration, bool) {
for _, option := range dashboardWindows {
if option.value == value {
return option.duration, true
}
}
return 0, false
}

func clampDashboardWindow(value string, maxWindow time.Duration) string {
requested, ok := dashboardWindowDuration(value)
if !ok || requested <= maxWindow {
return value
}
for index := len(dashboardWindows) - 1; index >= 0; index-- {
if dashboardWindows[index].duration <= maxWindow {
return dashboardWindows[index].value
}
}
return dashboardWindows[0].value
}

// normalizeStateIDs makes the service, rather than callers or the model, the
// authority for widget identifiers. Existing UUIDv7 values remain stable;
// omitted, descriptive, and legacy values are replaced and layout references
Expand Down
70 changes: 68 additions & 2 deletions internal/dashboard/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func TestServiceCreatesNamedOwnerScopedDashboards(t *testing.T) {
t.Fatal(err)
}
}
service := New(database.DB)
service := New(database.DB, 30)

initial, err := service.List(ctx, "owner-a")
if err != nil {
Expand Down Expand Up @@ -67,6 +67,65 @@ func TestServiceCreatesNamedOwnerScopedDashboards(t *testing.T) {
}
}

func TestServiceClampsDashboardWindowToRetention(t *testing.T) {
database, err := controlstore.NewSQLite(":memory:")
if err != nil {
t.Fatal(err)
}
defer database.Close()
ctx := context.Background()
if _, err := database.DB.ExecContext(ctx, `INSERT INTO users(id,email,name,role,active) VALUES('owner','owner@example.test','Owner','admin',1)`); err != nil {
t.Fatal(err)
}

state := DefaultState()
state.Filters.Window = "720h"
service := New(database.DB, 7)
created, err := service.Create(ctx, "owner", CreateInput{Name: "Long range", State: state})
if err != nil {
t.Fatal(err)
}
if created.State.Filters.Window != "168h" {
t.Fatalf("created window = %q, want 168h", created.State.Filters.Window)
}
var stored string
if err := database.DB.QueryRowContext(ctx, `SELECT window FROM dashboards WHERE id=?`, created.ID).Scan(&stored); err != nil {
t.Fatal(err)
}
if stored != "168h" {
t.Fatalf("stored window = %q, want 168h", stored)
}
created.State.Filters.Window = "720h"
updated, err := New(database.DB, 1).Update(ctx, "owner", created.ID, UpdateInput{Name: created.Name, State: created.State})
if err != nil {
t.Fatal(err)
}
if updated.State.Filters.Window != "24h" {
t.Fatalf("updated window = %q, want 24h", updated.State.Filters.Window)
}

// Dashboards saved before the retention setting was lowered must also be
// safe to render immediately, before the next edit persists the clamp.
if _, err := database.DB.ExecContext(ctx, `UPDATE dashboards SET window='720h' WHERE id=?`, created.ID); err != nil {
t.Fatal(err)
}
loaded, err := service.Get(ctx, "owner", created.ID)
if err != nil {
t.Fatal(err)
}
if loaded.State.Filters.Window != "168h" {
t.Fatalf("loaded window = %q, want 168h", loaded.State.Filters.Window)
}

unlimited, err := New(database.DB, 0).Get(ctx, "owner", created.ID)
if err != nil {
t.Fatal(err)
}
if unlimited.State.Filters.Window != "720h" {
t.Fatalf("unlimited-retention window = %q, want 720h", unlimited.State.Filters.Window)
}
}

func TestServiceMigratesLegacyCanvasOnFirstRead(t *testing.T) {
database, err := controlstore.NewSQLite(":memory:")
if err != nil {
Expand All @@ -81,7 +140,7 @@ func TestServiceMigratesLegacyCanvasOnFirstRead(t *testing.T) {
if _, err := database.DB.ExecContext(ctx, `INSERT INTO dashboard_state(owner_id,state_json) VALUES('owner',?)`, legacy); err != nil {
t.Fatal(err)
}
item, err := New(database.DB).Default(ctx, "owner")
item, err := New(database.DB, 30).Default(ctx, "owner")
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -117,6 +176,13 @@ func TestValidateRejectsInvalidStates(t *testing.T) {
if err := Validate("Baseline", "", valid()); err != nil {
t.Fatalf("baseline state rejected: %v", err)
}
for _, window := range []string{"168h", "720h"} {
state := valid()
state.Filters.Window = window
if err := Validate("Baseline", "", state); err != nil {
t.Fatalf("window %s rejected: %v", window, err)
}
}
cases := []struct {
name string
mutate func(*State)
Expand Down
42 changes: 21 additions & 21 deletions internal/mcp/apps/logs.html

Large diffs are not rendered by default.

26 changes: 13 additions & 13 deletions internal/mcp/apps/performance.html

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion internal/mcp/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func DescribeTools(ctx context.Context) ([]ToolDoc, error) {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()

server := NewWithIntelligence(nil, dashboard.New(nil), describeIntelligence{}, "docgen")
server := NewWithIntelligence(nil, dashboard.New(nil, 30), describeIntelligence{}, "docgen")

serverTransport, clientTransport := mcp.NewInMemoryTransports()

Expand Down
2 changes: 1 addition & 1 deletion internal/mcp/describe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func TestDescribeToolsMatchesWhatAClientIsServed(t *testing.T) {
t.Fatalf("DescribeTools: %v", err)
}

server := NewWithIntelligence(nil, dashboard.New(nil), describeIntelligence{}, "test")
server := NewWithIntelligence(nil, dashboard.New(nil, 30), describeIntelligence{}, "test")
session := connectTestClient(t, server, nil)
listed, err := session.ListTools(context.Background(), nil)
if err != nil {
Expand Down
8 changes: 4 additions & 4 deletions internal/mcp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,28 +33,28 @@ type IntelligenceSnapshots interface {
}

type QueryInput struct {
Window string `json:"window,omitempty" jsonschema:"Time window such as 15m, 1h, or 24h; defaults to 1h"`
Window string `json:"window,omitempty" jsonschema:"Time window such as 15m, 1h, 24h, 168h, or 720h; defaults to 1h"`
Namespace string `json:"namespace,omitempty" jsonschema:"OpenTelemetry service namespace; empty queries all namespaces"`
Limit int `json:"limit,omitempty" jsonschema:"Maximum services or edges to return, from 1 to 500"`
}

type PerformanceInput struct {
Window string `json:"window,omitempty" jsonschema:"Time window such as 15m, 1h, or 24h; defaults to 1h"`
Window string `json:"window,omitempty" jsonschema:"Time window such as 15m, 1h, 24h, 168h, or 720h; defaults to 1h"`
Namespace string `json:"namespace,omitempty" jsonschema:"OpenTelemetry service namespace; empty queries all namespaces"`
Service string `json:"service,omitempty" jsonschema:"Optional exact OpenTelemetry service name; omit for the whole system"`
Limit int `json:"limit,omitempty" jsonschema:"Maximum endpoints to return, from 1 to 500"`
}

type TraceInput struct {
Window string `json:"window,omitempty" jsonschema:"Trace lookup window such as 1h or 24h; defaults to 1h"`
Window string `json:"window,omitempty" jsonschema:"Trace lookup window such as 1h, 24h, 168h, or 720h; defaults to 1h"`
Namespace string `json:"namespace,omitempty" jsonschema:"OpenTelemetry service namespace; empty queries all namespaces"`
TraceID string `json:"trace_id,omitempty" jsonschema:"Exact trace ID; omit to inspect the most relevant recent error or slow trace"`
Service string `json:"service,omitempty" jsonschema:"Optional service filter when choosing a recent trace"`
Limit int `json:"limit,omitempty" jsonschema:"Maximum spans and correlated logs to return, from 1 to 500"`
}

type LogsInput struct {
Window string `json:"window,omitempty" jsonschema:"Time window such as 15m, 1h, or 24h; defaults to 1h"`
Window string `json:"window,omitempty" jsonschema:"Time window such as 15m, 1h, 24h, 168h, or 720h; defaults to 1h"`
Namespace string `json:"namespace,omitempty" jsonschema:"OpenTelemetry service namespace; empty queries all namespaces"`
Service string `json:"service,omitempty" jsonschema:"Optional exact OpenTelemetry service name"`
Severity string `json:"severity,omitempty" jsonschema:"Optional exact severity such as ERROR, WARN, or INFO"`
Expand Down
35 changes: 21 additions & 14 deletions internal/mcp/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func TestDashboardToolsUseAuthenticatedOwner(t *testing.T) {
if _, err := database.DB.ExecContext(ctx, `INSERT INTO users(id,email,name,role,active) VALUES('owner','owner@example.test','Owner','admin',1)`); err != nil {
t.Fatal(err)
}
server := New(&fakeObservability{}, dashboard.New(database.DB), "test")
server := New(&fakeObservability{}, dashboard.New(database.DB, 30), "test")
req := &mcp.CallToolRequest{Params: &mcp.CallToolParamsRaw{}, Extra: &mcp.RequestExtra{TokenInfo: &mcpgoauth.TokenInfo{UserID: "owner", Scopes: []string{dashboard.OAuthScope}}}}
state := dashboard.State{Filters: dashboard.Filters{Window: "1h"}, Widgets: []dashboard.Widget{{ID: "health", Type: "overview", Title: "System health", Enabled: true}}, Layout: []dashboard.Layout{{I: "health", X: 0, Y: 0, W: 12, H: 3}}}
_, output, err := server.dashboardCreate(ctx, req, DashboardCreateInput{Name: "AI overview", State: state})
Expand Down Expand Up @@ -70,7 +70,7 @@ func TestDashboardOwnerIgnoresSpoofedMetaWhenTokenPresent(t *testing.T) {
t.Fatal(err)
}
}
server := New(&fakeObservability{}, dashboard.New(database.DB), "test")
server := New(&fakeObservability{}, dashboard.New(database.DB, 30), "test")
// A remote client always carries TokenInfo (ProtectMCP guarantees it), so a
// spoofed _meta owner key must lose to the token identity.
req := &mcp.CallToolRequest{
Expand Down Expand Up @@ -139,18 +139,25 @@ func (f *fakeObservability) Logs(_ context.Context, scope observability.Scope, _
}

func TestOverviewReturnsSummaryAndStructuredOutput(t *testing.T) {
backend := &fakeObservability{}
s := New(backend, nil, "test")
s.now = func() time.Time { return time.Date(2026, 7, 20, 12, 0, 0, 0, time.UTC) }
result, output, err := s.overview(context.Background(), nil, QueryInput{Window: "15m", Namespace: "prod"})
if err != nil {
t.Fatalf("overview: %v", err)
}
if len(result.Content) != 1 || output.Schema != observability.OverviewSchema {
t.Fatalf("unexpected result: %#v %#v", result, output)
}
if got := backend.scope.End.Sub(backend.scope.Start); got != 15*time.Minute {
t.Fatalf("window = %s, want 15m", got)
for _, tt := range []struct {
window string
want time.Duration
}{{"15m", 15 * time.Minute}, {"720h", 30 * 24 * time.Hour}} {
t.Run(tt.window, func(t *testing.T) {
backend := &fakeObservability{}
s := New(backend, nil, "test")
s.now = func() time.Time { return time.Date(2026, 7, 20, 12, 0, 0, 0, time.UTC) }
result, output, err := s.overview(context.Background(), nil, QueryInput{Window: tt.window, Namespace: "prod"})
if err != nil {
t.Fatalf("overview: %v", err)
}
if len(result.Content) != 1 || output.Schema != observability.OverviewSchema {
t.Fatalf("unexpected result: %#v %#v", result, output)
}
if got := backend.scope.End.Sub(backend.scope.Start); got != tt.want {
t.Fatalf("window = %s, want %s", got, tt.want)
}
})
}
}

Expand Down
Loading
Loading