crowdsecurity/crowdsec · error

failed to count alerts per scenario: %w

Error message

failed to count alerts per scenario: %w

What it means

The ent GROUP BY (scenario) + COUNT aggregation query backing AlertsCountPerScenario failed at Scan time. The alert filter itself was built successfully; the failure is at DB execution — connection loss, timeout, or SQL error from the underlying database.

Source

Thrown at pkg/database/alerts.go:782

	return alertIDs, nil
}

func (c *Client) AlertsCountPerScenario(ctx context.Context, filter map[string][]string) (map[string]int, error) {
	var res []struct {
		Scenario string
		Count    int
	}

	query := c.Ent.Alert.Query()

	query, err := applyAlertFilter(query, filter)
	if err != nil {
		return nil, fmt.Errorf("failed to build alert request: %w", err)
	}

	err = query.GroupBy(alert.FieldScenario).Aggregate(ent.Count()).Scan(ctx, &res)
	if err != nil {
		return nil, fmt.Errorf("failed to count alerts per scenario: %w", err)
	}

	counts := make(map[string]int)

	for _, r := range res {
		counts[r.Scenario] = r.Count
	}

	return counts, nil
}

func (c *Client) TotalAlerts(ctx context.Context) (int, error) {
	return c.Ent.Alert.Query().Count(ctx)
}

func (c *Client) QueryAlertWithFilter(ctx context.Context, filter map[string][]string) ([]*ent.Alert, error) {
	sort := "DESC" // we sort by desc by default

View on GitHub (pinned to 909b515798)

Solutions

  1. Inspect the wrapped error for the driver-level cause
  2. Retry with a narrower time filter to reduce scan size
  3. Check DB health and slow-query logs
  4. Increase the caller's context timeout for large tables
Defensive patterns

Strategy: try-catch

Try / catch

counts, err := db.AlertsCountPerScenario(ctx, filter)
if err != nil {
    if errors.Is(err, context.DeadlineExceeded) {
        // retry with longer timeout / narrower filter
    }
    return err
}

Prevention

When it happens

Trigger: The ent Scan call fails: DB unreachable, driver error, or context cancelled while aggregating alerts per scenario.

Common situations: Large alerts table making the GROUP BY slow enough to hit a context deadline; DB migration in progress; connection pool exhaustion under concurrent LAPI queries.

Understand the failure class

Background: "query failed", "%w: SQL error" — wrapped database query errors in Go libraries explained — this error's family across 3 libraries.

Related errors


AI-assisted analysis of crowdsecurity/crowdsec@909b515798 (2026-09-06). Data as JSON: /api/errors/95da1f60feb5c373. Report an issue: GitHub.