pipecd icon indicating copy to clipboard operation
pipecd copied to clipboard

ANALYSIS stage can falsely succeed without running any metric queries when duration <= interval

Open harshalsp07 opened this issue 1 month ago • 0 comments

What happened:

In the pipedv1 analysis plugin, an ANALYSIS stage can complete with status SUCCESS without ever running any metric query or evaluating any threshold.

This happens when the stage's duration is shorter than (or expires before) the metric check's interval. For example, configuring an analysis stage with duration: 30s and a metric with interval: 1m (or when a shared template sets an interval longer than the stage duration):

  1. AnalysisStageOptions.Validate() accepts the configuration without verifying that duration >= interval.
  2. At runtime, metricsAnalyzer.run(ctx) initializes a ticker:
    ticker := time.NewTicker(a.cfg.Interval.Duration())
    defer ticker.Stop()
    
    In Go, time.NewTicker does not fire immediately; it waits for the full interval before sending the first event on ticker.C.
  3. When the stage timeout expires, the context is cancelled and run(ctx) catches <-ctx.Done():
    case <-ctx.Done():
        return nil
    
  4. It returns nil without having executed a single query or evaluation.
  5. In analysis.go, the orchestrating errgroup sees no errors (eg.Wait() == nil), so it logs:
    e.logPersister.Success("All analyses were successful")
    return status // sdk.StageStatusSuccess
    

Because no error is returned, the deployment safety gate passes unconditionally—even if the underlying service is throwing errors or metric values violate the configured threshold.

What you expected to happen:

An analysis stage configured to guard a deployment should never pass without performing an actual check:

  • Configuration validation should reject stages where duration < interval (both during initial stage validation and after template resolution).
  • At runtime, the analyzer should ensure at least one evaluation was performed before considering the stage successful, or run the first query on startup before ticking.

How to reproduce it:

A focused unit test in executestage reproduces the behavior deterministically:

  1. Configure an AnalysisStageOptions with a duration of 20ms and a metric check with interval: 1s, threshold max: 1.0, and failureLimit: 0.
  2. Provide a mock metrics provider that returns Value: 100 (which would immediately fail the threshold if evaluated).
  3. Call stage.Validate(): it succeeds with no error.
  4. Call analyzer.run(ctx): it returns nil without making any calls to the provider (p.calls == 0).
Reproduction unit test
package executestage

import (
	"context"
	"testing"
	"time"

	"github.com/pipe-cd/pipecd/pkg/app/pipedv1/plugin/analysis/analysisprovider/metrics"
	"github.com/pipe-cd/pipecd/pkg/app/pipedv1/plugin/analysis/config"
	"github.com/pipe-cd/piped-plugin-sdk-go/unit"
	"go.uber.org/zap"
)

type countingFailingProvider struct{ calls int }

func (p *countingFailingProvider) Type() string { return "test" }
func (p *countingFailingProvider) QueryPoints(context.Context, string, metrics.QueryRange) ([]metrics.DataPoint, error) {
	p.calls++
	return []metrics.DataPoint{{Value: 100}}, nil // Should fail max: 1.0 threshold
}

func TestAnalysisCanSucceedWithoutQuery(t *testing.T) {
	max := 1.0
	cfg := config.AnalysisMetrics{
		Provider:  "test",
		Query:     "test",
		Strategy:  config.AnalysisStrategyThreshold,
		Deviation: "EITHER",
		Interval:  unit.Duration(time.Second),
		Expected:  config.AnalysisExpected{Max: &max},
	}
	stage := config.AnalysisStageOptions{
		Duration: unit.Duration(20 * time.Millisecond),
		Metrics:  []config.TemplatableAnalysisMetrics{{AnalysisMetrics: cfg}},
	}

	if err := stage.Validate(); err != nil {
		t.Fatalf("configuration rejected: %v", err)
	}

	p := &countingFailingProvider{}
	a := &metricsAnalyzer{
		id:           "test",
		cfg:          cfg,
		provider:     p,
		logger:       zap.NewNop(),
		logPersister: &fakeLogPersister{},
	}

	ctx, cancel := context.WithTimeout(context.Background(), stage.Duration.Duration())
	defer cancel()

	if err := a.run(ctx); err != nil {
		t.Fatalf("analyzer failed: %v", err)
	}

	if p.calls != 0 {
		t.Fatalf("expected 0 calls due to duration < interval, got %d", p.calls)
	}

	// Analyzer returned nil (success) despite zero queries and a provider that would violate thresholds!
}

Relevant Code:

Environment:

  • piped version: master
  • control-plane version: master
  • OS: Linux

Possible Solution / Recommendations:

  1. Validation: Validate that stage.Duration >= metric.Interval in stage.go (and validate resolved configurations if using templates).
  2. Initial Check / Execution Count: In metricsAnalyzer (and generic analyzer), run an immediate evaluation on startup before waiting for subsequent ticks, or track the number of successful checks performed and return an error if evaluatedCount == 0 when ctx.Done() is reached.

harshalsp07 avatar Oct 30 '26 05:10 harshalsp07