Alert Processing Engine
Functional Specification
1. Overview & Purpose
This document defines the functional requirements for the CommandIT Alert Processing Engine. This engine serves as the central component responsible for receiving alerts from various sources within the CommandIT platform (including parsed emails from the AI Email Triage Agent, direct RMM agent events, SNMP traps, API integrations), processing these alerts based on defined policies and rules, managing alert state (including frequency, duration, and flapping thresholds), and executing automated actions such as ticket creation, remediation scripts, or notifications, while respecting maintenance windows.
The primary goals are to:
- Standardize alert handling across different monitoring sources.
- Reduce alert noise by suppressing redundant or flapping alerts using stateful processing and thresholds.
- Automate responses and remediation actions based on configurable policies.
- Ensure actions respect maintenance windows and defined policies, with override capabilities.
- Provide consistent logging and context for processed alerts.
2. Core Principles
- Stateful Processing: Tracks the state of unique alert conditions over time using the Alerts table.
- Policy-Driven: Actions, thresholds, and overrides are determined by configurable, hierarchical policies (AlertProcessingPolicies).
- Extensible: Designed to handle diverse alert inputs and trigger various defined actions.
- Context-Aware: Considers CI relationships, organizational structure, and maintenance schedules.
- Integrated: Works closely with CommandIT's PSA (Tickets), RMM (Devices, AgentCommandQueue), Automation (Scripts), Notification (NotificationProfiles), and Policy modules.
- Efficient: Architecture favors asynchronous processing and optimized state management where feasible.
3. Inputs & Alert Sources
- Input Format: The engine expects alert data in a standardized JSON format upon invocation. Adherence is mandatory. (See Appendix A for full structure).
- Input Validation: Reject alerts missing mandatory fields (alertTimestampUTC, severity, ciIdentifiers.orgId, message). Log error, return 'ProcessingFailed: Invalid Input'.
- Potential Sources: AI Email Triage Agent, RMM Agent events, SNMP Trap Listener, API Integrations, Internal Checks. Sources must format data correctly.
- Allowed condition_logic Fields: The field names usable in AlertProcessingRules.condition_logic are derived directly from the standardized input JSON structure (Section 3 / Appendix A). Final list validation required during implementation.
4. Core Processing Workflow
- Receive & Validate Alert: Ingest standardized alert data, perform schema validation. Log & reject if invalid.
- Parse Alert Signature: Generate unique alert_signature string based on applicable rule definition (Section 5). Log failure & reject if signature cannot be generated.
- Policy Lookup: Determine effective AlertProcessingPolicy via hierarchy (Section 6). Use default if none found.
- Rule Evaluation Loop: Iterate through policy's AlertProcessingPolicyRules by priority.
- Condition Match: Evaluate alert data against AlertProcessingRules.condition_logic (Section 6). If no match, continue.
- If Rule Matches:
- Check Clearing Condition: Evaluate alert against rule's clear_condition_logic. If match -> Execute Clearing Logic (Section 11). STOP Processing.
- Check Flapping State: Evaluate recent state changes against flapping thresholds (Section 7). If flapping detected -> Update Alerts.status to 'Suppressed_Flapping', log suppression. STOP Processing.
- Check Maintenance Window: Evaluate against applicable MaintenanceWindows (Section 8). Check rule's ignore_maintenance_windows flag. If suppression applies -> Update Alerts.status to 'Suppressed_Maint', log suppression. STOP Processing.
- Process Active Alert State & Thresholds: Query/Update Alerts table state (Section 5). Check frequency/duration thresholds (Section 7).
- Execute Action (If Threshold Met & Ready): If thresholds met AND Alerts.action_taken_flag is false -> Execute Action (Section 9). Update Alerts.action_taken_flag=true and potentially Alerts.status.
- Update Alert State: Update Alerts record (timestamps, count, final status).
- Log & Return: Log processing details (AuditLog, AlertActionsLog). Return outcome status. Break Rule Loop & STOP.
- No Matching Rule / Fallback: If loop completes, apply default behavior (e.g., log alert, optionally create low-priority informational ticket). Log outcome. Return status.
5. Alert Signature & State Management
- Alert Signature Definition (AlertProcessingRules.alert_signature_definition): Uses a JSON array defining source components to concatenate into the alert_signature string. See Appendix A for schema details.
- Signature Generation Implementation: Concatenate extracted, non-empty strings using pipe (|). Recommended: Apply SHA-256 hash to the final string and store the hex hash in Alerts.alert_signature (TEXT/VARCHAR(64)).
- State Tracking (Alerts Table): Uses alert_signature as the key to track state. Key fields: status, first_occurred_at, last_occurred_at, occurrence_count, last_status_change_timestamp, action_taken_flag, related_ticket_id.
- State Update Logic: Query Alerts for active match on alert_signature. If found, update timestamps/count. If not found, create new Alerts record. Update status based on outcomes. Reset action_taken_flag when status becomes 'Resolved'.
- State Transitions (Alerts.status): Defined statuses: 'New', 'Acknowledged', 'TicketCreated', 'ActionAttempted', 'ActionSucceeded', 'ActionFailed', 'Suppressed_Maint', 'Suppressed_Flapping', 'ProcessingError', 'Resolved', 'Closed', 'Unknown'. Transitions follow workflow logic. (Schema constraint needs update for 'ProcessingError').
5.1. Alert Record Retention & Purging/Archiving
- Purpose: To prevent the primary Alerts table from growing indefinitely with inactive records, ensuring optimal query performance for state tracking and flapping detection.
- Target Records: Records in the Alerts table with a final inactive status (primarily 'Resolved', 'Closed'). Aged records in error states ('Unknown', 'ProcessingError') should also be considered.
- Retention Period:
- Requirement: A configurable retention period (System Setting, likely MSP/Platform level) MUST define how long inactive alerts remain in the primary Alerts table before being eligible for purging or archiving.
- Dependency: This period MUST be longer than the maximum possible sum of flapping_threshold_window_seconds + flapping_clear_delay_seconds used in any active policy, plus a safety buffer (e.g., 24 hours).
- Recommendation (Resolved/Closed): Default retention period: 90 days after resolved_at or closed_at. This provides a balance between retaining recent history and managing table size.
- Recommendation (Error States): Recommend a separate, likely longer, configurable default retention period (e.g., 180 days based on updated_at) for purging alerts stuck in 'Unknown' or 'ProcessingError' statuses.
- Mechanism:
- Recommended: A Scheduled Database Job managed by the CommandIT platform.
- Implementation Tool: Use the database's native scheduler (e.g., pg_cron) or a platform-level scheduler.
- Frequency: Recommend Daily execution during defined off-peak hours.
- Process (Purge vs. Archive):
- Recommendation: Implement Purging (DELETE) as the default initial strategy due to lower complexity. Implement archiving (to Alerts_Archive or data warehouse) only if long-term raw alert history is a defined requirement.
- Purge Implementation: Job executes DELETE statements in batches (configurable size, e.g., 10000) using appropriate WHERE clauses based on status and timestamp against configured retention periods. Handle error statuses separately. Job repeats until no more eligible rows are found in a pass or a time limit is reached.
- Archive Implementation (If Chosen): Requires Alerts_Archive table. Job uses transactional INSERT...SELECT...; DELETE...; pattern in batches. Requires archive lifecycle management.
- Job Error Handling & Monitoring: The cleanup job MUST log its own errors. Failures MUST trigger administrative alerts. Monitor job duration, rows processed, and Alerts table size.
- Configuration: Retention periods (Resolved/Closed, Errors), batch size, and Purge/Archive choice MUST be configurable CommandIT system settings.
6. Policy & Rule Evaluation
- Policy Hierarchy: Effective AlertProcessingPolicy determined by lookup: Alert Endpoint -> Location -> Org -> Global Default using direct FK links.
- Rule Matching: Incoming alert data evaluated against AlertProcessingRules.condition_logic (See Appendix A).
- Priority & Conflict Resolution: AlertProcessingPolicyRules.priority dictates order. The first matching rule determines the action and maintenance override behavior.
7. Threshold & Flapping Evaluation
- Flapping Detection:
- Trigger: Before Threshold Evaluation for 'New' alerts.
- Input: Reads policy thresholds (flapping_threshold_count, flapping_threshold_window_seconds, flapping_clear_delay_seconds).
- History Query Strategy: Query the Alerts table itself for recent status changes associated with the alert_signature within the time window (using last_status_change_timestamp). Requires effective indexing and data retention (Sec 5.1). Application logic analyzes the result sequence to count relevant Resolved -> Active transitions. (Dedicated history table is future optimization).
- Action: If transition_count >= flapping_threshold_count -> Set Alerts.status to 'Suppressed_Flapping', log suppression (AuditLog), stop action processing.
- Clearing Flap: Check performed when the next 'New' alert arrives for a signature in 'Resolved' status. Compare NOW() - Alerts.resolved_at against flapping_clear_delay_seconds. If delay met, process as new; otherwise, keep 'Resolved' and suppress incoming alert.
- Threshold Evaluation:
- Trigger: After rule match & passed flapping/maintenance checks.
- Input: Rule action_parameters (trigger_after_occurrences, etc.).
- Logic: Compare parameters against Alerts record state.
- Outcome: Determine if action execution should proceed.
8. Maintenance Window Checks
- Trigger: Before executing actions ('CreateTicket', 'RunScript', etc.).
- Logic: Query active MaintenanceWindows. If active window applies: Check ignore_maintenance_windows flag on matched rule.
- Action: If suppression applies, set Alerts.status to 'Suppressed_Maint', log suppression (AuditLog), skip action. If override applies, log override to AuditLog, proceed to action.
- Permissions: Setting ignore_maintenance_windows=true requires specific RBAC permission.
9. Action Execution
- Trigger: Rule matched, thresholds met, not suppressed, Alerts.action_taken_flag is false.
- Process: Execute action using action_parameters (See Appendix A). Call CommandIT tools/APIs (See Appendix B). Log attempt/outcome (AlertActionsLog). Set Alerts.action_taken_flag = true. Update Alerts.status.
- Supported Actions: 'Ignore', 'CreateTicket', 'RouteToBoard', 'UpdateExistingCI', 'RunScript', 'SendNotification', 'CallWebhook'.
10. Clearing Condition Handling
- Trigger: Incoming alert matches a rule's clear_condition_logic.
- Action: Find active Alerts record. Update Alerts.status to 'Resolved', set resolved_at, reset action_taken_flag. Optionally add note to linked ticket. Log 'Processed_AlertCleared'.
11. Error Handling & Retry Strategy
- Logging: Log ALL internal engine errors comprehensively (tag 'AlertEngineError').
- Alert State: Update Alerts.status to 'ProcessingError' on unrecoverable error if possible.
- Return Status: Return 'ProcessingFailed:{error}' to caller.
- Retry Mechanism: Implement limited (max 3), exponential backoff retries for defined transient errors. Log retries. If retries fail, log definitively, set error status, return failure.
- Retryable Examples: DB Timeout/Deadlock, Temp Network Error to internal APIs, HTTP 503/504/429 from internal APIs, Temp Object Storage Unavailability.
- Non-Retryable Examples: Invalid Input Schema, Signature Generation Failure, Config Errors (Invalid IDs), Permanent API Errors (4xx except 429), Script Execution Failure (non-zero exit), Policy Check Failure.
- Administrative Alerting Strategy:
- Primary: Configure CommandIT MonitoringRule checking engine errors (AuditLog or Alerts status). Threshold: e.g., > 5 errors in 15 min (configurable). Action: SendNotification to critical admin NotificationProfile/DistributionGroup. Content Recommendation: Include Engine Name, Timestamp, Error, Signature/Rule ID.
- Fallback (Optional): Direct critical failure push to external alerting system.
- Maintenance: Recommend quarterly review of engine error logs and alerting thresholds.
12. Logging
- Alert State: Alerts table lifecycle tracking.
- Action Execution: AlertActionsLog table for initiated actions.
- Overall Processing Outcome: Engine provides disposition status to caller (logged in EmailProcessingLog).
- Engine Diagnostics: Detailed internal step logging (configurable level).
- Key Events: Maintenance Overrides, Flapping Suppressions logged to AuditLog.
- Audit Log Format for Engine Events:
- MAINTENANCE_OVERRIDE: action_type='MAINTENANCE_OVERRIDE', target_entity_type='Alert', target_entity_id=alert_id/signature, change_details={rule_id, policy_id, window_id, suppressed_action}.
- FLAPPING_SUPPRESSION: action_type='FLAPPING_SUPPRESSION', target_entity_type='Alert', target_entity_id=alert_id/signature, change_details={policy_id, threshold_count, threshold_window}.
- RULE_ACTION_EXECUTED: action_type='RULE_ACTION_EXECUTED', target_entity_type='Alert', target_entity_id=alert_id, change_details={rule_id, policy_id, action_name, action_parameters, action_log_id}.
- ALERT_STATUS_CHANGE: action_type='ALERT_STATUS_CHANGE', target_entity_type='Alert', target_entity_id=alert_id, change_details={old_status, new_status, reason}.
- ENGINE_ERROR: action_type='ALERT_ENGINE_ERROR', target_entity_type='AlertProcessingEngine', target_entity_id=alert_signature/input_ref, change_details={error_message, processing_step}.
13. User Interface Requirements
- 13.1. Alert Rule Definitions UI: List view; Add/Edit modal with builders for Condition Logic, Alert Signature Definition, Clear Condition Logic.
- 13.2. Alert Policy Definitions UI: List view; Add/Edit modal with fields for policy details; Ordered list of linked rules; Link/Edit Rule modal with Rule Selector and Dynamic Action Parameters Builder (incl. Thresholds, flapping settings, action fields, ignore_maintenance_windows).
- 13.3. Alert Policy Assignment UI: Integrated into Org/Location/Alert Endpoint screens via dropdown selector.
- 13.4. Monitoring Engine Activity UI: Log view (EmailProcessingLog, engine logs/AuditLog) with filtering/searching. Links to Alerts/Tickets.
- 13.5. Main Alerts Monitoring Screen: Dashboard/List of active Alerts. Key columns, filtering, sorting, actions.
- 13.6. Individual Alert Detail View: Modal/Screen showing all Alerts fields, context, history, notes, related items, actions.
- 13.7. UI Builder Functional Requirements: Condition/Signature/Action builders must be intuitive, dynamic, provide selectors, include validation, clearly represent logic.
14. Scalability Considerations
- Asynchronous Input: Use a message queue for alert ingestion.
- Stateless Instances (Recommended): Design engine instances relying on Alerts table for state. Address concurrency.
- Database Optimization: Index Alerts effectively. Partition if needed. Purge/archive old resolved/closed alerts regularly (as per Sec 5.1).
- Asynchronous Actions: Offload slow actions (RunScript, CallWebhook, SendNotification) to separate worker queues.
15. Deployment Strategy
- Phased Rollout: The CommandIT platform MUST support enabling new/modified AlertProcessingPolicies or engine versions for specific test Orgs/Locations before global activation.
- Versioning: Consider implementing versioning for AlertProcessingPolicies and AlertProcessingRules to track history and facilitate rollback. Changes MUST be auditable in AuditLog.
- Testing Environment: A dedicated staging environment closely mirroring production MUST be used for validation.
- "Dry Run" / "Report Only" Mode: The engine MUST support a "Dry Run" mode (configurable per-policy or globally) where it logs actions it would have taken without executing them.
- Engine Service Updates: Use standard Blue/Green or Canary releases for the engine service. Monitor health and error rates closely post-deployment.
Appendix A: Detailed JSON Schemas for Rules
A.1. AlertProcessingRules.condition_logic Structure:
// Top Level Object
{
"match_operator": "AND | OR", // Required
"criteria": [ // Required: Array of Criterion Objects
{
"field": "<Standardized Input Field Path>", // Required. e.g., "severity", "ciIdentifiers.hostname", "details.parsedParameters.InstanceName"
"operator": "<Comparison Operator>", // Required. e.g., "equals", "contains", "regex_match", "greater_than"
"value": "string | number | boolean | Array<string>", // Required. Value for comparison.
"case_sensitive": "boolean (Optional, Default: false)"
} //...
]
}A.2. AlertProcessingRules.alert_signature_definition Structure:
[ // Array of Signature Component Objects
{
"source": "'static' | 'ciIdentifiers' | 'message' | 'details'", // Required
"value": "<String literal (if source is 'static')>",
"field": "<Field name within source object (if source != 'static' and not regex)>",
"regex_capture": "<Regex pattern with one capture group (if source is 'message' or 'details')>",
"required": "boolean (Default: true)",
"transform": "'lowercase' | 'uppercase' | 'none' (Default: 'none')"
}
// ... more component objects ...
]A.3. AlertProcessingPolicyRules.action_parameters Structure:
// Base Structure includes optional thresholds & clear condition
{
// --- Thresholds (Optional) ---
"trigger_after_occurrences": "<Integer >= 1, Optional>", // Default: 1
"trigger_occurrence_window_seconds": "<Integer >= 0, Optional>", // Default: 0 (no window)
"trigger_after_duration_seconds": "<Integer >= 0, Optional>", // Default: 0 (immediate)
"clear_condition_logic": { /* Optional: Same structure as condition_logic */ },
// --- Action-Specific Parameters (Only relevant keys included based on 'action') ---
// If action = 'CreateTicket':
"ticket_template_id": "<String: UUID, Required>",
"priority_id": "<Integer, Optional>", "status_id": "<String: UUID, Optional>", "assigned_user_id": "<String: UUID, Optional>", "target_board_id": "<String: UUID, Optional>",
// If action = 'RunScript':
"script_id": "<String: UUID, Required>",
"script_parameters": { /* JSON Object, Optional */ },
"target_device_context": "'AlertDevice' | 'SpecificDevice' | 'ProbeDevice', Optional, Default: 'AlertDevice'",
"specific_device_id": "<String: UUID, Optional>", // Required if target_device_context='SpecificDevice'
// If action = 'SendNotification':
"notification_profile_id": "<String: UUID, Required>",
"notification_template_id_override": "<String: UUID, Optional>",
// If action = 'CallWebhook':
"webhook_url": "<String, Required>",
"webhook_method": "'POST' | 'GET' | 'PUT', Optional, Default: 'POST'",
"webhook_payload_template": { /* JSON Object/Template, Optional */ },
"webhook_headers": { /* JSON Object, Optional */ },
// If action = 'RouteToBoard':
"target_board_id": "<String: UUID, Required>",
// If action = 'UpdateExistingCI':
"ci_identifier_field": "<String, Required>",
"ci_identifier_regex": "<String, Optional>",
"ci_type": "<String, Required>",
"max_ticket_age_days": "<Integer, Optional, Default: 30>",
"update_status_to": "<String: UUID, Optional>",
"add_internal_note": "<Boolean, Optional, Default: true>"
// Note: 'Ignore' action has null or empty action_parameters beyond optional thresholds/clear condition.
}Appendix B: Conceptual API Contracts for Engine Actions
(High-level examples; formal specs like OpenAPI/gRPC needed for implementation)
- createTicket(ticketData: Dict) -> {ticket_id: int, ticket_number: str}
- updateTicket(ticketId: int | ticketNumber: str, updates: Dict) -> {success: bool}
- executeRMMScript(deviceId: UUID, scriptId: UUID, ...) -> {command_queue_id: int, initial_status: str} (Engine needs way to get final result from queue)
- triggerNotification(profileId: UUID, ...) -> {success: bool, ...}
- callWebhook(url: str, ...) -> {status_code: int, ..., success: bool}
- getAlertState(alertSignature: str) -> Dict | None (Queries Alerts table for active alert)
- updateAlertState(alertId: int | alertSignature: str, updates: Dict) -> {success: bool} (Updates fields in Alerts)
- createAlertRecord(alertData: Dict) -> {alert_id: int} (Inserts new record into Alerts)
- checkMaintenanceWindow(...) -> {is_active: bool, ...}
- logAuditEvent(auditData: Dict) -> {success: bool} (Writes to AuditLog)
- queryAlertHistory(alertSignature: str, ...) -> List[Dict] (Used for flapping check)