The post has been translated automatically. Original language: Russian
Taken from the main technical channel of Postgres DBA (Corrections are possible in the original article).
The beginning of work :
Continuation: predicting an incident, after conducting a full cycle of Markov chain training on a productive load.

Fig.1 Zabbix dashboard
GitHub repository - description of the Markov chain implementation (in the process of editing):
Markov chain for predicting emergency situations

Detailed interpretation of Markov chain prediction results
1. The structure of the output data of all predictive functions
All functions (mchain_predict_risk_1min, mchain_predict_risk_k, wrappers for 15, 30, 60 minutes) return a set of four fields:
risk (REAL)
- The probability of an accident (falling into an emergency state) on a given horizon. The value is from 0.0 to 1.0.
curr_situation (TEXT)
- A situation code explaining how the risk was received. Possible values:
- 'unknown_state'
- 'no_risk'
- 'risk_calculated'
curr_transitions_to_risk (INT)
- The number of direct transitions from the current state to any emergency state recorded in the trained probability matrix.
curr_total_transitions_known (INT)
- The total number of different target states that can be reached from the current state (according to the model).
2. Interpretation of the risk field
Numerical meaning
- risk is an estimate of the conditional probability that the system will be in an emergency state at least once in a specified number of minutes (1, 15, 30, 60).
- For mchain_predict_risk_1min, the probability of switching in the next minute.
- For mchain_predict_risk_k, the probability of at least one accident in k steps (minutes), calculated using an absorbing Markov chain.
Range of values
- 0.0 – according to the model, an accident is impossible (there are no transitions to emergency states).
- 0.05 is used as an a priori probability in the case when the current state of the model is unknown (situation unknown_state).
- >0.0 – the model estimates a non-zero risk.
Practical interpretation (risk levels)
- < 0.01 (<1%) – the risk is extremely low, the system is stable.
- 0.01 – 0.10 (1%-10%) – moderate risk, monitoring is recommended.
- 0.10 – 0.30 (10%-30%) – There is a significant risk, it is advisable to take preventive measures.
- > 0.30 (>30%) – high risk, requires immediate intervention.
Important: Forecasts depend on the trained model and may be unreliable if the model has a low confidence rating (see section 6).
3. Interpretation of the curren_situation field
The field provides the context for calculating the risk and helps diagnose why the model has given a particular value.
3.1 'unknown_state'
When it occurs
- The current performance metrics (current_correlation, os_trend, wait_trend) are missing (for example, the cluster_stat_median table is empty).
- Or the current state is not found in the state_descriptions directory (almost impossible if all 189 combinations are filled in).
- Or there are no records for this condition in the markov_probabilities table (the condition has never been encountered in training).
Which means
- The model does not know how the system behaves from this state. An a priori probability of 0.05 (1–(0.95)^k for a multistep forecast) is returned. The forecast is unreliable.
What to do
- Wait for transitions from this state to accumulate via mchain_train_step. If the condition appears frequently, but the model does not recognize it, check whether fill_state_descriptions() is called and whether the frequency tables have been reset.
3.2 'no_risk'
When it occurs
- The current state is known, but there is not a single transition from it to emergency states in the markov_probabilities probability matrix. That is, curr_transitions_to_risk = 0.
Which means
- According to the accumulated data (including forgetting), there has never been a direct transition from the current state to an accident. the risk is returned as 0.0 (even for a multistep forecast, because an absorbing matrix in the absence of initial transitions will give zero probability).
Degree of confidence
- High, but only if the model is sufficiently trained (confidence rating ≥3). If there is a small amount of data, it may be false (an accident is possible, but has not yet occurred).
3.3 'risk_calculated'
When it occurs
- The current state is known, and the model has at least one transition from it to the emergency state (curr_transitions_to_risk > 0). The risk is calculated based on probabilities from markov_probabilities (for 1 minute) or via an absorbing chain (for k steps).
Which means
- The model generated an estimate based on actual observed statistics. This is the main operating mode.
4. Interpretation of the curr_transitions_to_risk and curr_total_transitions_known fields
These fields help to assess how statistically reliable the forecast is.
curr_transitions_to_risk
- How many different emergency states are achievable from the current state in one step.
- The higher this number, the greater the variety of accident scenarios.
- Not to be confused with probability: even if curr_transitions_to_risk = 10, but each of these branches has a very low probability, the final risk may be low.
curr_total_transitions_known
- The total number of target states that can be switched from the current state (including non-emergency ones).
- If this number is small (for example, 1-3), the model has a poor idea of the behavior of the system from this state – the forecast may be inaccurate.
- If the number is large (close to 189), it means that the condition was often encountered and many different transitions were observed from it – the forecast is more reliable.
Recommendation: Keep an eye on situations where curren_total_transitions_known is less than 5-10. In such cases, the forecast should be treated with caution, even if curren_situation = 'risk_calculated'.
5. Features of multistep forecasts (15, 30, 60 minutes)
How it works: The functions mchain_predict_risk_15min, etc. call mchain_predict_risk_k(k) with the corresponding k.
Mathematically, An absorbing Markov chain is used, where all emergency states are made absorbing (you cannot get out of them, the probability of remaining is 1). The risk for k steps is the probability of being in any absorbing state after k transitions.
Interpretation over horizons
- 15 minutes is a short–term danger, useful for immediate reactions.
- 30 minutes is a medium–term trend.
- 1 hour – shows how prone the system is to an accident in principle (stationary behavior).
Important property:
- For a multistep forecast, the risk does not have to monotonously increase with k, because the model may have recurrent non-emergency states. However, in most real cases, the risk increases over the horizon, but it can become saturated.
6. How to take into account the reliability of forecasts (reliability rating)
The mchain_forecast_reliability() function returns a rating from 0 to 5. Interpretation:
- 0 – The model is not trained (less than 100 transitions). Forecasts should not be used.
- 1 – Very little data (100-499). Forecasts are almost random.
- 2 – Insufficient data (500-4999). Forecasts are unstable, you can only watch the trend.
- 3 is minimally sufficient, but drifts are possible. Forecasts can be used withbe careful, especially at low risks.
- 4 – Good reliability. Forecasts can be trusted in most situations.
- 5 – Excellent reliability. Forecasts are as reliable as possible.
Recommended threshold for decision-making: rating ≥ 3. With a rating of 0-2, any predictions should be treated as experimental.
7. The impact of adaptive forgetting on interpretation
What is forgetting: The frequency of transitions is periodically multiplied by a factor (1 - alpha), where alpha can be fixed or adaptive (depending on the time elapsed since the last incident).
How does this affect forecasts
- The model forgets old observations. The forecast reflects only recent history (recent days–weeks, depending on alpha and the forgetting interval).
- If there have been no incidents for a long time, alpha decreases to min_alpha (for example, 0.01) – forgetting slows down, the model retains a longer memory.
- After the incident, alpha temporarily increases – the model quickly "forgets" the behavior that preceded the incident and adapts to the new conditions.
Interpretation in case of active forgetting
- A risk forecast is a current trend, not an all–time average statistic. If the system has changed dramatically (for example, after a software update), adaptive forgetting will allow forecasts to reflect the new reality within a few days.
8. A complete example of practical interpretation
Let's say the call mchain_predict_risk_15min() returned:
- risk = 0.23
- curr_situation = 'risk_calculated'
- curr_transitions_to_risk = 4
- curr_total_transitions_known = 32
Decoding:
- risk = 0.23 – the probability of an accident in the next 15 minutes is 23%. This is a significant risk.
- the situation is risk_calculated – the forecast is based on real data from the model.
- 4 emergency transitions – there are 4 different ways to get into an accident in 1 minute from the current state. This indicates a variety of ways to cause an accident.
- There are 32 known target states – the model has studied the behavior from the current state quite well (rich statistics).
- The confidence rating (a separate call to mchain_forecast_reliability) is assumed to be 4 – the forecast can be trusted.
Conclusion: The system is in a state with a real and well-founded threat of an accident. Actions should be taken to stabilize performance.
9. Recommendations for monitoring
- Integrate mchain_health_check() into your monitoring system. It will return the OK, WARNING, or CRITICAL status with an explanation if something is wrong (no transitions, forgetting doesn't work, high crash rate).
- Periodically request mchain_reliability_report() to evaluate the quality of the model.
- Keep an eye on the unknown_state situation. If it occurs frequently, it indicates problems with collecting metrics or the appearance of new, previously unseen correlation/trend combinations.
- Use forecasts as an early warning indicator, but make decisions about switching operating modes or automatic intervention based on the reliability rating and additional rules (for example, only if the risk is > 0.2 and the rating is ≥ 3).
Thus, the provided implementation provides not just a number, but a full-fledged diagnostic package that allows the operator or the automatic system to understand how much the forecast can be trusted and what are its statistical bases.
Взято с основного технического канала Postgres DBA (Возможны исправления в исходной статье).
Начало работ :
Продолжение : прогнозирование инцидента , после проведения полного цикла обучения цепи Маркова на продуктивной нагрузке.

Рис.1 Дашборд панель Zabbix
Репозиторий GitHub - описание реализации цепи Маркова (в процессе редактирования):
Цепь Маркова для прогнозирования аварийных ситуаций

Подробная интерпретация результатов прогнозов цепи Маркова
1. Структура выходных данных всех прогнозных функций
Все функции (mchain_predict_risk_1min, mchain_predict_risk_k, обёртки для 15, 30, 60 минут) возвращают набор из четырёх полей:
risk (REAL)
- Вероятность аварии (попадания в аварийное состояние) на заданном горизонте. Значение от 0.0 до 1.0.
curr_situation (TEXT)
- Код ситуации, объясняющий, как был получен риск. Возможные значения:
- 'unknown_state'
- 'no_risk'
- 'risk_calculated'
curr_transitions_to_risk (INT)
- Количество прямых переходов из текущего состояния в любое аварийное состояние, зафиксированных в обученной матрице вероятностей.
curr_total_transitions_known (INT)
- Общее число различных целевых состояний, в которые можно перейти из текущего состояния (согласно модели).
2. Интерпретация поля risk
Числовой смысл
- risk – это оценка условной вероятности того, что за указанное количество минут (1, 15, 30, 60) система хотя бы один раз окажется в аварийном состоянии.
- Для mchain_predict_risk_1min – вероятность перехода на следующей минуте.
- Для mchain_predict_risk_k – вероятность хотя бы одного попадания в аварию за k шагов (минут), вычисленная через поглощающую цепь Маркова.
Диапазон значений
- 0.0 – согласно модели, авария невозможна (нет переходов в аварийные состояния).
- 0.05 – используется как априорная вероятность в случае, когда текущее состояние модели неизвестно (ситуация unknown_state).
- >0.0 – модель оценивает ненулевой риск.
Практическая интерпретация (уровни риска)
- < 0.01 (<1%) – риск крайне низкий, система стабильна.
- 0.01 – 0.10 (1%–10%) – умеренный риск, рекомендуется мониторинг.
- 0.10 – 0.30 (10%–30%) – значительный риск, желательно принять превентивные меры.
- > 0.30 (>30%) – высокий риск, требуется немедленное вмешательство.
Важно: Прогнозы зависят от обученной модели и могут быть недостоверны, если модель имеет низкий рейтинг достоверности (см. раздел 6).
3. Интерпретация поля curr_situation
Поле даёт контекст вычисления риска и помогает диагностировать, почему модель выдала то или иное значение.
3.1 'unknown_state'
Когда возникает
- Текущие метрики производительности (current_correlation, os_trend, wait_trend) отсутствуют (например, таблица cluster_stat_median пуста).
- Или текущее состояние не найдено в справочнике state_descriptions (практически невозможно, если заполнены все 189 комбинаций).
- Или в таблице markov_probabilities нет записей для данного состояния (состояние ни разу не встречалось в обучении).
Что означает
- Модель не знает, как ведёт себя система из данного состояния. Возвращается априорная вероятность 0.05 (1–(0.95)^k для многошагового прогноза). Прогноз недостоверен.
Что делать
- Дождаться, пока через mchain_train_step накопятся переходы из этого состояния. Если состояние появляется часто, но модель его не узнаёт – проверить, вызывается ли fill_state_descriptions() и не сброшены ли таблицы частот.
3.2 'no_risk'
Когда возникает
- Текущее состояние известно, но в матрице вероятностей markov_probabilities нет ни одного перехода из него в аварийные состояния. То есть curr_transitions_to_risk = 0.
Что означает
- Согласно накопленным данным (с учётом забывания), из текущего состояния никогда не было прямого перехода в аварию. risk возвращается как 0.0 (даже для многошагового прогноза, потому что поглощающая матрица при отсутствии исходных переходов даст нулевую вероятность).
Степень уверенности
- Высокая, но только если модель достаточно обучена (рейтинг достоверности ≥3). При малом объёме данных может быть ложным (авария возможна, но ещё не встречалась).
3.3 'risk_calculated'
Когда возникает
- Текущее состояние известно, и в модели есть хотя бы один переход из него в аварийное состояние (curr_transitions_to_risk > 0). Риск вычислен на основе вероятностей из markov_probabilities (для 1 минуты) или через поглощающую цепь (для k шагов).
Что означает
- Модель сформировала оценку на основе реально наблюдавшейся статистики. Это основной рабочий режим.
4. Интерпретация полей curr_transitions_to_risk и curr_total_transitions_known
Эти поля помогают оценить, насколько статистически обеспечен прогноз.
curr_transitions_to_risk
- Сколько различных аварийных состояний достижимо из текущего состояния за один шаг.
- Чем больше это число, тем выше разнообразие сценариев аварии.
- Не следует путать с вероятностью: даже если curr_transitions_to_risk = 10, но каждая из этих веток имеет очень малую вероятность, итоговый risk может быть низким.
curr_total_transitions_known
- Общее число целевых состояний, в которые можно перейти из текущего состояния (включая неаварийные).
- Если это число мало (например, 1–3), модель имеет бедное представление о поведении системы из данного состояния – прогноз может быть неточным.
- Если число велико (близко к 189), значит состояние часто встречалось и из него наблюдалось много разнообразных переходов – прогноз более надёжен.
Рекомендация: Следить за ситуациями, когда curr_total_transitions_known меньше 5–10 – в таких случаях к прогнозу стоит относиться с осторожностью, даже если curr_situation = 'risk_calculated'.
5. Особенности многошаговых прогнозов (15, 30, 60 минут)
Как работают: Функции mchain_predict_risk_15min и т.д. вызывают mchain_predict_risk_k(k) с соответствующим k.
Математически: Используется поглощающая цепь Маркова, где все аварийные состояния сделаны поглощающими (из них нельзя выйти, вероятность остаться = 1). Риск за k шагов – это вероятность оказаться в любом поглощающем состоянии после k переходов.
Интерпретация по горизонтам
- 15 минут – краткосрочная опасность, полезен для немедленных реакций.
- 30 минут – среднесрочный тренд.
- 1 час – показывает, насколько система склонна к аварии в принципе (стационарное поведение).
Важное свойство:
- Для многошагового прогноза риск не обязан монотонно расти с k, потому что модель может иметь возвратные неаварийные состояния. Однако в большинстве реальных случаев риск с горизонтом растёт, но может насыщаться.
6. Как учитывать достоверность прогнозов (рейтинг надёжности)
Функция mchain_forecast_reliability() возвращает рейтинг от 0 до 5. Интерпретация:
- 0 – Модель не обучена (менее 100 переходов). Прогнозы не использовать.
- 1 – Очень мало данных (100–499). Прогнозы практически случайны.
- 2 – Недостаточно данных (500–4999). Прогнозы нестабильны, можно смотреть только тренд.
- 3 – Минимально достаточно, но возможны дрейфы. Прогнозы можно использовать с осторожностью, особенно при низких рисках.
- 4 – Хорошая достоверность. Прогнозам можно доверять в большинстве ситуаций.
- 5 – Отличная достоверность. Прогнозы максимально надёжны.
Рекомендуемый порог для принятия решений: рейтинг ≥ 3. При рейтинге 0–2 любые прогнозы следует воспринимать как экспериментальные.
7. Влияние адаптивного забывания на интерпретацию
Что такое забывание: Частоты переходов периодически умножаются на коэффициент (1 - alpha), где alpha может быть фиксированным или адаптивным (зависит от времени, прошедшего с последнего инцидента).
Как это сказывается на прогнозах
- Модель забывает старые наблюдения. Прогноз отражает только недавнюю историю (последние дни–недели, в зависимости от alpha и интервала забывания).
- Если инцидентов давно не было, alpha снижается до min_alpha (например, 0.01) – забывание замедляется, модель сохраняет более длинную память.
- После инцидента alpha временно повышается – модель быстро «забывает» поведение, предшествовавшее инциденту, и адаптируется к новым условиям.
Интерпретация при активном забывании
- Прогноз риска – это текущая тенденция, а не усреднённая статистика за всё время. Если система кардинально изменилась (например, после обновления ПО), адаптивное забывание позволит прогнозам отразить новую реальность в течение нескольких дней.
8. Полный пример практической интерпретации
Допустим, вызов mchain_predict_risk_15min() вернул:
- risk = 0.23
- curr_situation = 'risk_calculated'
- curr_transitions_to_risk = 4
- curr_total_transitions_known = 32
Расшифровка:
- risk = 0.23 – вероятность аварии в ближайшие 15 минут составляет 23%. Это значительный риск.
- ситуация risk_calculated – прогноз построен на реальных данных из модели.
- 4 аварийных перехода – из текущего состояния есть 4 разных варианта попасть в аварию за 1 минуту. Это говорит о разнообразии путей к аварии.
- известно 32 целевых состояния – модель достаточно хорошо изучила поведение из текущего состояния (богатая статистика).
- рейтинг достоверности (отдельный вызов mchain_forecast_reliability) предположим равен 4 – прогнозу можно доверять.
Вывод: Система находится в состоянии с реальной и хорошо обоснованной угрозой аварии. Следует предпринять действия по стабилизации производительности.
9. Рекомендации по мониторингу
- Интегрируйте mchain_health_check() в вашу систему мониторинга. Она вернёт статус OK, WARNING или CRITICAL с пояснением, если что-то не так (нет переходов, забывание не работает, высокий рост аварий).
- Периодически запрашивайте mchain_reliability_report() для оценки качества модели.
- Следите за ситуацией unknown_state – если она возникает часто, это указывает на проблемы со сбором метрик или на появление новых, ранее не виденных комбинаций корреляции/трендов.
- Используйте прогнозы как индикатор раннего предупреждения, но решения о переключении режимов работы или автоматическом вмешательстве принимайте с учётом рейтинга достоверности и дополнительных правил (например, только если риск > 0.2 и рейтинг ≥ 3).
ℹ️Таким образом, предоставленная реализация даёт не просто число, а полноценный диагностический пакет, позволяющий оператору или автоматической системе понять, насколько можно доверять прогнозу и каковы его статистические основания.