{"record":{"id":"d05c6272e3582510","repo":"crowdsecurity/crowdsec","slug":"unable-to-get-alerts-count-w","errorCode":null,"errorMessage":"unable to get alerts count: %w","messagePattern":"unable to get alerts count: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"pkg/database/flush.go","lineNumber":328,"sourceCode":"\t\tdeletedByNbItem int\n\t\ttotalAlerts     int\n\t\terr             error\n\t)\n\n\tif !c.TryFlushLock() {\n\t\tc.Log.Debug(\"a list is being imported, flushing later\")\n\t\treturn nil\n\t}\n\tdefer c.FlushUnlock()\n\n\tc.Log.Debug(\"Flushing orphan alerts\")\n\tc.FlushOrphans(ctx)\n\tc.Log.Debug(\"Done flushing orphan alerts\")\n\n\ttotalAlerts, err = c.TotalAlerts(ctx)\n\tif err != nil {\n\t\tc.Log.Warningf(\"FlushAlerts (max items count): %s\", err)\n\t\treturn fmt.Errorf(\"unable to get alerts count: %w\", err)\n\t}\n\n\tc.Log.Debugf(\"FlushAlerts (Total alerts): %d\", totalAlerts)\n\n\tif maxAge != 0 {\n\t\tnow := time.Now().UTC()\n\n\t\t// Delete alerts older than maxAge, but never one that still has an\n\t\t// active decision (the cascade would take the live decision with it).\n\t\tnbDeleted, err := c.Ent.Alert.Delete().Where(\n\t\t\talert.CreatedAtLTE(now.Add(-maxAge)),\n\t\t\talertWithoutActiveDecision(now),\n\t\t).Exec(ctx)\n\t\tif err != nil {\n\t\t\tc.Log.Warningf(\"FlushAlerts (max age): %s\", err)\n\t\t\treturn fmt.Errorf(\"unable to flush alerts older than %s: %w\", maxAge, err)\n\t\t}\n","sourceCodeStart":310,"sourceCodeEnd":346,"githubUrl":"https://github.com/crowdsecurity/crowdsec/blob/909b5157986a2b2c2163300fdaef5ed01289f7d2/pkg/database/flush.go#L310-L346","documentation":"FlushAlerts needs the total alert count to enforce the max_items limit. When c.TotalAlerts fails (a database query error), the function logs a warning and returns this wrapped error instead of proceeding with the flush.","triggerScenarios":"The underlying ent query for the alerts count fails: database unreachable, connection dropped mid-query, schema/table 'alerts' missing, or a context timeout/cancel during the count query.","commonSituations":"SQLite file locked by another process (concurrent cscli commands), Postgres/MySQL restarted, network interruption to a remote DB, or the database schema not migrated after an upgrade.","solutions":["Check database connectivity and that the DB process is running (e.g. systemctl status postgresql / mysql).","If using SQLite, ensure no other process holds the DB file lock and the file path is writable.","Run cscli database migrate (or restart crowdsec) to ensure the schema is up to date after a version upgrade.","Inspect the wrapped error (%w) for the driver-specific message (e.g. 'connection refused', 'no such table') and address that.","For repeated failures, verify db_config credentials and network reachability in crowdsec's config.yaml."],"exampleFix":"// check DB is reachable before/when debugging\n// before: silently failing remote DB\ndb_config:\n  type: postgresql\n  host: 10.0.0.5\n// after: fix host/port and credentials, then verify\ndb_config:\n  type: postgresql\n  host: 10.0.0.5\n  port: 5432\n  user: crowdsec\n  password: correct-password\n  db_name: crowdsec","handlingStrategy":"try-catch","validationCode":"// probe connectivity before running flushes\nif err := c.Ent.Alert.Query().Limit(1).Exec(ctx); err != nil {\n    return fmt.Errorf(\"database unreachable: %w\", err)\n}","typeGuard":"if c == nil || c.Ent == nil {\n    return errors.New(\"database client not initialized\")\n}","tryCatchPattern":"if err := c.FlushAlerts(ctx, maxAge, maxItems); err != nil {\n    if strings.Contains(err.Error(), \"unable to get alerts count\") {\n        // database query failed; check connectivity and retry later\n    }\n    return err\n}","preventionTips":["Monitor database health and connection pool saturation.","Avoid running concurrent cscli operations against the same SQLite file.","Run schema migrations on upgrade before the scheduler starts.","Set sane DB timeouts so counts fail fast rather than hang."],"tags":["go","database","crowdsec","flush"],"backgroundTag":"database-query-failed","analyzedSha":"909b5157986a2b2c2163300fdaef5ed01289f7d2","analyzedAt":"2026-09-06T12:27:26.012Z","contentChangedAt":"2026-09-06T12:27:26.012Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}