historecon 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. historecon-0.2.0/.github/workflows/ci.yml +59 -0
  2. historecon-0.2.0/.github/workflows/release.yml +67 -0
  3. historecon-0.2.0/.gitignore +10 -0
  4. historecon-0.2.0/CHANGELOG.md +14 -0
  5. historecon-0.2.0/Dockerfile +7 -0
  6. historecon-0.2.0/LICENSE +17 -0
  7. historecon-0.2.0/PKG-INFO +466 -0
  8. historecon-0.2.0/README.md +432 -0
  9. historecon-0.2.0/docker-compose.yml +26 -0
  10. historecon-0.2.0/docs/deployment.md +75 -0
  11. historecon-0.2.0/docs/releasing.md +18 -0
  12. historecon-0.2.0/pyproject.toml +48 -0
  13. historecon-0.2.0/src/historecon/__init__.py +40 -0
  14. historecon-0.2.0/src/historecon/alerting.py +250 -0
  15. historecon-0.2.0/src/historecon/baseline.py +151 -0
  16. historecon-0.2.0/src/historecon/classifier.py +24 -0
  17. historecon-0.2.0/src/historecon/config.py +127 -0
  18. historecon-0.2.0/src/historecon/dashboard.py +272 -0
  19. historecon-0.2.0/src/historecon/engine.py +182 -0
  20. historecon-0.2.0/src/historecon/incidents.py +114 -0
  21. historecon-0.2.0/src/historecon/model_monitor.py +169 -0
  22. historecon-0.2.0/src/historecon/models.py +66 -0
  23. historecon-0.2.0/src/historecon/normalize.py +60 -0
  24. historecon-0.2.0/src/historecon/notifications.py +327 -0
  25. historecon-0.2.0/src/historecon/observability.py +73 -0
  26. historecon-0.2.0/src/historecon/postgres_store.py +126 -0
  27. historecon-0.2.0/src/historecon/regression.py +483 -0
  28. historecon-0.2.0/src/historecon/settings.py +56 -0
  29. historecon-0.2.0/src/historecon/worker.py +37 -0
  30. historecon-0.2.0/tests/test_alerting.py +86 -0
  31. historecon-0.2.0/tests/test_baseline.py +533 -0
  32. historecon-0.2.0/tests/test_dashboard.py +92 -0
  33. historecon-0.2.0/tests/test_historecon.py +103 -0
  34. historecon-0.2.0/tests/test_incidents.py +63 -0
  35. historecon-0.2.0/tests/test_model_monitor.py +88 -0
  36. historecon-0.2.0/tests/test_notifications.py +175 -0
  37. historecon-0.2.0/tests/test_observability.py +21 -0
  38. historecon-0.2.0/tests/test_postgres_store.py +155 -0
  39. historecon-0.2.0/tests/test_settings.py +24 -0
@@ -0,0 +1,59 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+
7
+ jobs:
8
+ test:
9
+ runs-on: ubuntu-22.04
10
+ services:
11
+ postgres:
12
+ image: postgres:16
13
+ env:
14
+ POSTGRES_DB: historecon_test
15
+ POSTGRES_USER: historecon
16
+ POSTGRES_PASSWORD: historecon
17
+ ports:
18
+ - 5432:5432
19
+ options: >-
20
+ --health-cmd "pg_isready -U historecon -d historecon_test"
21
+ --health-interval 5s
22
+ --health-timeout 3s
23
+ --health-retries 10
24
+ strategy:
25
+ matrix:
26
+ python-version: ["3.9", "3.10", "3.11", "3.12"]
27
+ env:
28
+ HISTORECON_TEST_DATABASE_URL: postgresql://historecon:historecon@localhost:5432/historecon_test
29
+ steps:
30
+ - uses: actions/checkout@v4
31
+ - uses: actions/setup-python@v5
32
+ with:
33
+ python-version: ${{ matrix.python-version }}
34
+ - run: python -m pip install --upgrade pip
35
+ - run: python -m pip install -e ".[dev,postgres,pandas]"
36
+ - run: pytest
37
+
38
+ package:
39
+ runs-on: ubuntu-22.04
40
+ strategy:
41
+ matrix:
42
+ python-version: ["3.9", "3.10", "3.11", "3.12"]
43
+ steps:
44
+ - uses: actions/checkout@v4
45
+ - uses: actions/setup-python@v5
46
+ with:
47
+ python-version: ${{ matrix.python-version }}
48
+ - run: python -m pip install build twine
49
+ - run: python -m build
50
+ - run: python -m twine check --strict dist/*
51
+ - name: Verify wheel and source distribution in isolated environments
52
+ run: |
53
+ for artifact in dist/*.whl dist/*.tar.gz; do
54
+ python -m venv "$RUNNER_TEMP/historecon-smoke"
55
+ "$RUNNER_TEMP/historecon-smoke/bin/python" -m pip install "$artifact"
56
+ "$RUNNER_TEMP/historecon-smoke/bin/python" -m pip check
57
+ (cd "$RUNNER_TEMP" && "$RUNNER_TEMP/historecon-smoke/bin/python" -I -c 'from historecon import DiagnosticEngine, __version__; assert __version__ == "0.2.0"; assert DiagnosticEngine().analyze([]).observations_analyzed == 0')
58
+ rm -rf "$RUNNER_TEMP/historecon-smoke"
59
+ done
@@ -0,0 +1,67 @@
1
+ name: Publish to PyPI
2
+ on:
3
+ push:
4
+ tags:
5
+ - 'v*'
6
+ permissions:
7
+ contents: read
8
+ jobs:
9
+ validate:
10
+ runs-on: ubuntu-22.04
11
+ services:
12
+ postgres:
13
+ image: postgres:16
14
+ env:
15
+ POSTGRES_DB: historecon_test
16
+ POSTGRES_USER: historecon
17
+ POSTGRES_PASSWORD: historecon
18
+ ports:
19
+ - 5432:5432
20
+ options: >-
21
+ --health-cmd "pg_isready -U historecon -d historecon_test"
22
+ --health-interval 5s
23
+ --health-timeout 3s
24
+ --health-retries 10
25
+ env:
26
+ HISTORECON_TEST_DATABASE_URL: postgresql://historecon:historecon@localhost:5432/historecon_test
27
+ steps:
28
+ - uses: actions/checkout@v4
29
+ with:
30
+ fetch-depth: 0
31
+ - uses: actions/setup-python@v5
32
+ with:
33
+ python-version: '3.12'
34
+ - name: Verify release commit belongs to main
35
+ run: git merge-base --is-ancestor HEAD origin/main
36
+ - run: python -m pip install -e ".[dev,postgres,pandas]"
37
+ - name: Verify version and tag
38
+ run: |
39
+ python -c 'import os, tomllib, historecon; v = tomllib.load(open("pyproject.toml", "rb"))["project"]["version"]; assert v == historecon.__version__; assert os.environ["GITHUB_REF_NAME"] == "v" + v'
40
+ - run: pytest
41
+ - run: python -m build
42
+ - run: python -m twine check --strict dist/*
43
+ - name: Smoke test installed wheel
44
+ run: |
45
+ python -m venv "$RUNNER_TEMP/release-smoke"
46
+ "$RUNNER_TEMP/release-smoke/bin/python" -m pip install dist/*.whl
47
+ "$RUNNER_TEMP/release-smoke/bin/python" -m pip check
48
+ (cd "$RUNNER_TEMP" && "$RUNNER_TEMP/release-smoke/bin/python" -I -c 'from historecon import DiagnosticEngine; assert DiagnosticEngine().analyze([]).observations_analyzed == 0')
49
+ - uses: actions/upload-artifact@v4
50
+ with:
51
+ name: distributions
52
+ path: dist/
53
+ if-no-files-found: error
54
+ publish:
55
+ needs: validate
56
+ runs-on: ubuntu-22.04
57
+ environment:
58
+ name: pypi
59
+ url: https://pypi.org/project/historecon/
60
+ permissions:
61
+ id-token: write
62
+ steps:
63
+ - uses: actions/download-artifact@v4
64
+ with:
65
+ name: distributions
66
+ path: dist/
67
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,10 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .pytest_cache/
4
+ .ruff_cache/
5
+ .venv/
6
+ venv/
7
+ dist/
8
+ build/
9
+ *.egg-info/
10
+ .coverage
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 (planned)
4
+
5
+ Initial public beta.
6
+
7
+ - Historian-neutral data-quality and signal diagnostics with evidence and suggested investigation ownership.
8
+ - Historical median/MAD baselines with operating-mode and load conditioning.
9
+ - Optional regression diagnostics with chronological validation, load-local screening intervals and model-health monitoring.
10
+ - Persistent alert lifecycle, webhook/Slack/Teams adapters, retries and HTML health reports.
11
+ - Optional PostgreSQL persistence with per-delivery transaction claims for competing notification workers, environment settings, structured logging and deployment examples.
12
+ - Package metadata, build verification and trusted-publishing workflow.
13
+
14
+ Limitations: single alert writer per stream; JSONL dispatchers are single-process, at-least-once delivery, in-memory diagnostic processing, evolving beta APIs. Findings require domain validation and are not process safety decisions.
@@ -0,0 +1,7 @@
1
+ FROM python:3.12-slim
2
+ ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
3
+ WORKDIR /app
4
+ COPY pyproject.toml README.md ./
5
+ COPY src ./src
6
+ RUN pip install --no-cache-dir ".[postgres]"
7
+ CMD ["python", "-m", "historecon.worker"]
@@ -0,0 +1,17 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Historecon contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
@@ -0,0 +1,466 @@
1
+ Metadata-Version: 2.5
2
+ Name: historecon
3
+ Version: 0.2.0
4
+ Summary: Explainable diagnostics for industrial time-series data
5
+ Project-URL: Homepage, https://github.com/panwarnalini-hub/historecon
6
+ Project-URL: Repository, https://github.com/panwarnalini-hub/historecon
7
+ Project-URL: Issues, https://github.com/panwarnalini-hub/historecon/issues
8
+ Project-URL: Documentation, https://github.com/panwarnalini-hub/historecon#readme
9
+ Project-URL: Changelog, https://github.com/panwarnalini-hub/historecon/blob/main/CHANGELOG.md
10
+ Author: Historecon contributors
11
+ License: MIT
12
+ License-File: LICENSE
13
+ Keywords: data-quality,diagnostics,historian,industrial-iot,time-series
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Topic :: Scientific/Engineering
23
+ Requires-Python: >=3.9
24
+ Provides-Extra: dev
25
+ Requires-Dist: build>=1; extra == 'dev'
26
+ Requires-Dist: pytest>=7; extra == 'dev'
27
+ Requires-Dist: ruff>=0.5; extra == 'dev'
28
+ Requires-Dist: twine>=5; extra == 'dev'
29
+ Provides-Extra: pandas
30
+ Requires-Dist: pandas>=1.5; extra == 'pandas'
31
+ Provides-Extra: postgres
32
+ Requires-Dist: psycopg[binary]>=3.1; extra == 'postgres'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # Historecon
36
+
37
+ **Explainable diagnostics for industrial time-series data.**
38
+
39
+ Historecon analyses historian-style observations and produces evidence-backed findings for data-quality events, stale/frozen/noisy signals, engineering-limit violations, unusual rates of change, time-correlated failures and deviations from an independent historical reference.
40
+
41
+ It is historian- and platform-neutral. The core package has no mandatory third-party dependencies and accepts Python dictionaries/records. Version 0.2.0 is a public beta; API and persistence formats may evolve. Pandas support is optional.
42
+
43
+ > **Important:** Historecon identifies patterns that warrant investigation. It does not prove physical root cause, instrument failure, or process safety conditions. Validate findings with domain experts and source-system semantics.
44
+
45
+ ## Install
46
+
47
+ Supported Python versions: 3.9–3.12 (tested on Linux). Before the first PyPI publication, install from the source checkout using `python -m pip install .`.
48
+
49
+ ```bash
50
+ pip install historecon
51
+ ```
52
+
53
+ For Pandas input:
54
+
55
+ ```bash
56
+ pip install "historecon[pandas]"
57
+ ```
58
+
59
+ ## Quick start
60
+
61
+ ```python
62
+ from historecon import DiagnosticConfig, DiagnosticEngine
63
+
64
+ current = [
65
+ {"tag": "PUMP_101", "timestamp": "2026-12-01T06:00:00Z", "value": 15.2, "status": "Good"},
66
+ ]
67
+ historical = [
68
+ {"tag": "PUMP_101", "timestamp": "2026-11-30T06:00:00Z", "value": 10.0, "status": "Good"},
69
+ {"tag": "PUMP_101", "timestamp": "2026-11-29T06:00:00Z", "value": 10.1, "status": "Good"},
70
+ # Supply enough representative historical points for each tag.
71
+ ]
72
+ config = DiagnosticConfig(baseline_min_points=20, baseline_z_threshold=3.5)
73
+ report = DiagnosticEngine(config).analyze(current, baseline_data=historical)
74
+ for finding in report.findings:
75
+ print(finding.diagnostic_type, finding.affected_tags)
76
+ print(finding.evidence, finding.recommended_action)
77
+ ```
78
+
79
+ The baseline is supplied separately from current observations. Historecon does not use the current diagnostic window to build its own reference.
80
+
81
+ ## Input schema
82
+
83
+ Each observation is a mapping or record with:
84
+
85
+ | Field | Required | Meaning |
86
+ |---|---:|---|
87
+ | `tag` | yes | Stable tag/series identifier |
88
+ | `timestamp` | yes | ISO-8601 string, `datetime`, or Unix timestamp |
89
+ | `value` | no | Numeric or categorical measurement; null is retained |
90
+ | `status` | no | Original source quality/status label |
91
+ | `sampling_interval_seconds` | no | Expected update interval for this tag |
92
+ | `engineering_min` | no | Optional lower engineering limit |
93
+ | `engineering_max` | no | Optional upper engineering limit |
94
+ | `source` | no | Optional source/interface identifier |
95
+ | `is_recorded` | no | Whether value is recorded rather than interpolated; defaults to `True` |
96
+ | `operating_mode` | no | Optional categorical operating state, e.g. `RUNNING` or `RECIRCULATION_ON` |
97
+ | `operating_load` | no | Optional numeric load/context value used for load bands and regression conditioning (keep units consistent per tag) |
98
+
99
+ Additional fields are ignored. Original input status is retained in finding evidence.
100
+
101
+ ## Capabilities
102
+
103
+ - Configurable known-good, bad, questionable, communication, equipment and access status labels.
104
+ - Named source-specific status profiles with explicit category and routing overrides.
105
+ - Bounded status incidents with per-tag timelines and event counts.
106
+ - Stale-series detection using per-observation sampling interval or global configuration.
107
+ - Frozen-value detection on recorded numeric observations only.
108
+ - Basic variability detection using configurable population standard deviation.
109
+ - Engineering range violations when limits are supplied.
110
+ - Rate-of-change detection when a threshold is configured.
111
+ - Cross-tag status correlation using anchored time windows.
112
+ - Historical baseline deviation segmented by tag, operating mode and configurable continuous-load bands, using median and robust spread (MAD, with IQR fallback).
113
+ - Optional load-conditioned linear regression baselines with robust residual screening.
114
+ - Suggested investigation ownership and evidence attached to every finding.
115
+
116
+ Unrecognised status labels are `UNKNOWN`; users should supply source-specific mappings. Alarm labels are not automatically classified as bad quality.
117
+
118
+ ## Source-specific status profiles
119
+
120
+ Use a named profile when a historian, gateway, or application has its own status vocabulary. Only labels explicitly mapped are classified by the profile; unlisted labels remain `UNKNOWN`.
121
+
122
+ ```python
123
+ from historecon import DiagnosticConfig, DiagnosticEngine, StatusProfile
124
+ from historecon.models import StatusCategory
125
+
126
+ profile = StatusProfile(
127
+ name="plant-historian",
128
+ mappings={
129
+ "Vendor Comm Lost": StatusCategory.COMMUNICATION_FAILURE,
130
+ "Sensor Input Invalid": StatusCategory.BAD_QUALITY,
131
+ },
132
+ owner_overrides={"COMMUNICATION_FAILURE": "INTEGRATION_TEAM"},
133
+ )
134
+ config = DiagnosticConfig(status_profile=profile, incident_gap_seconds=300)
135
+ report = DiagnosticEngine(config).analyze(current)
136
+ ```
137
+
138
+ Status events for each tag and category are split into incidents when the next event falls outside the configured window measured from the first event in that incident. This prevents a long chain of nearby events from stretching one incident indefinitely.
139
+
140
+ ## Historical baselines
141
+
142
+ Call `analyze(current_data, baseline_data=historical_data)` to compare current values with an independent historical reference.
143
+
144
+ - Baselines are calculated independently per tag.
145
+ - The default minimum is 20 eligible historical points.
146
+ - The center is the historical median.
147
+ - Spread is estimated using median absolute deviation (MAD), with an interquartile-range fallback.
148
+ - If historical spread is zero, a non-zero deviation is flagged only when it meets the configured absolute-deviation tolerance.
149
+ - Only recorded numeric observations with `GOOD` or missing status are eligible for the baseline and current comparison. Known bad, questionable, unknown and interpolated observations are excluded.
150
+ - Consecutive deviations are grouped into bounded incidents.
151
+
152
+ Example configuration:
153
+
154
+ ```python
155
+ config = DiagnosticConfig(
156
+ baseline_min_points=20,
157
+ baseline_z_threshold=3.5,
158
+ baseline_min_deviation=0.5,
159
+ baseline_zero_spread_tolerance=0.5,
160
+ baseline_incident_gap_seconds=300,
161
+ )
162
+ report = DiagnosticEngine(config).analyze(current_data, baseline_data=historical_data)
163
+ ```
164
+
165
+ The robust score is a screening statistic, not a probability or proof of abnormal equipment. When `operating_load` is provided, the default `baseline_load_band_width=5.0` groups numeric loads into half-open bands such as [40, 45) and [45, 50). Load units are defined by your input data; use consistent units for a given tag in current and historical data. Each comparison requires the same tag, categorical mode and load band. Historecon does not fall back to neighbouring or pooled load bands when history is insufficient. Set `baseline_load_band_width=None` to disable load segmentation. If `operating_mode` is supplied, each tag is compared only with historical observations carrying the same mode label (matching is case-insensitive). Historecon deliberately does not fall back to a pooled tag baseline when a mode has insufficient history; it skips that comparison instead of mixing unlike operating states.
166
+
167
+ Example: derive a stable mode label from process context (such as a validated load band or equipment state) and include it on both current and historical rows:
168
+
169
+ ```python
170
+ current_data = [
171
+ {"tag": "PUMP_101_FLOW", "timestamp": "2026-12-01T06:00:00Z", "value": 120.0,
172
+ "status": "Good", "operating_mode": "HIGH_LOAD"},
173
+ ]
174
+ historical_data = [
175
+ {"tag": "PUMP_101_FLOW", "timestamp": "2026-11-30T06:00:00Z", "value": 118.5,
176
+ "status": "Good", "operating_mode": "HIGH_LOAD"},
177
+ # Include enough representative HIGH_LOAD points for this tag.
178
+ ]
179
+ report = DiagnosticEngine(config).analyze(current_data, baseline_data=historical_data)
180
+ ```
181
+
182
+ You can use a composite label when several dimensions define a state, for example `HIGH_LOAD|RECIRCULATION_ON`. Historecon does not infer operating modes from raw process values: derive and validate those labels in your data preparation layer. Load bands approximate continuous conditioning; they do not interpolate between load values or model trends within a band. Narrower bands increase specificity but require more history. Wider bands provide more samples but may mix different operating behaviour. A regression-based conditional baseline is a possible later extension.
183
+
184
+
185
+ ### Load-conditioned regression (optional)
186
+
187
+ Enable a separate regression diagnostic when the expected signal value changes continuously with operating load. The existing median/MAD load-band baseline remains available and unchanged; regression is opt-in and emits a distinct finding type.
188
+
189
+ ```python
190
+ config = DiagnosticConfig(
191
+ baseline_regression_enabled=True,
192
+ baseline_regression_min_points=30,
193
+ baseline_regression_z_threshold=3.5,
194
+ baseline_regression_min_deviation=0.0,
195
+ )
196
+ report = DiagnosticEngine(config).analyze(
197
+ current_data,
198
+ baseline_data=historical_data,
199
+ )
200
+ ```
201
+
202
+ Both historical and current rows need a numeric `operating_load`. Historecon fits a per-tag, per-operating-mode ordinary least-squares line from eligible historical observations, then screens current residuals using robust residual spread (MAD, with IQR fallback). Bad-quality, unknown-status and interpolated observations are excluded. It requires enough historical points and load variation, and does not extrapolate beyond the historical load range. The report summary also exposes a `regression_model_validation` entry for each tag/mode group, even when no anomaly finding is emitted. Each entry includes `model_reliability_status` so downstream systems can gate or qualify use of the diagnostic. Validation uses expanding-window walk-forward predictions: each validation segment is predicted only from earlier historical observations. Missing operating modes are grouped only with other missing-mode observations.
203
+
204
+ Regression findings use the distinct type `LOAD_CONDITIONAL_REGRESSION_DEVIATION` and include the fitted intercept/slope, historical load range, predicted values, residuals, robust scale and thresholds. The method is a screening diagnostic, not a physical model: validate linearity, residual patterns, operating-state coverage and process context before relying on it. It does not currently model nonlinear load relationships, interactions between multiple process variables, time dependence or uncertainty in the fitted prediction.
205
+
206
+ The regression diagnostic is disabled by default. Its default minimum history is 30 points. It can run alongside the existing band-based diagnostic; set `baseline_load_band_width=None` if you want to disable band comparisons independently.
207
+
208
+ Validation uses expanding-window walk-forward predictions. It reports out-of-sample RMSE and R-squared, compares linear and quadratic candidate RMSE, and selects the quadratic model only when its holdout RMSE improves by at least `baseline_regression_nonlinear_improvement` (default 15%). The default minimum R-squared for an acceptable fit is 0.5. Residual robust scale is compared between lower- and higher-load halves; a ratio at or above `baseline_regression_variance_ratio_threshold` (default 3.0) marks possible load-dependent variance. This is a transparent screening heuristic, not a formal statistical test.
209
+
210
+ Walk-forward absolute prediction errors are used to calculate a finite-sample, conformal-style prediction interval conditioned on operating load. For each current load, Historecon selects a neighbourhood of calibration errors at nearby loads and calculates a local upper quantile, allowing intervals to widen where historical errors are larger. The default target coverage is 95%, configurable with `baseline_regression_prediction_interval_coverage`; the minimum local neighbourhood defaults to 20 and is configurable with `baseline_regression_interval_min_points`. Current prediction intervals are exposed in `regression_model_validation` under `current_prediction_intervals`. A current point must fall outside its load-local interval and meet the existing robust residual and minimum-deviation criteria before a regression anomaly is emitted. If there are too few chronological holdout predictions to calibrate an interval, Historecon reports insufficient calibration and does not emit regression anomaly findings for that group. This deliberately favours withholding a claim over treating model uncertainty as an equipment anomaly. The interval is an empirical screening interval, not a guaranteed coverage promise under serial dependence or distribution shift. Local calibration can fall back to the full available calibration set when too few nearby errors are available; if the sample cannot support the requested upper quantile, the interval is withheld rather than fabricated. This is a simple nearest-load calibration strategy, not a formal conditional-conformal guarantee.
211
+
212
+ Model reliability is reported independently from individual anomaly findings:
213
+
214
+ | Status | Meaning |
215
+ |---|---|
216
+ | `TRUSTWORTHY` | Walk-forward fit meets the configured quality threshold and a prediction interval is available; no current-window residual shift was detected. |
217
+ | `WEAK_FIT` | Walk-forward fit quality is below the configured R-squared threshold, or validation is insufficient to establish a reliable fit. |
218
+ | `INSUFFICIENT_CALIBRATION` | There are not enough walk-forward errors to support the requested prediction interval. |
219
+ | `DISTRIBUTION_SHIFT_SUSPECTED` | A sufficiently large current window has a median signed residual materially different from the walk-forward calibration residuals. |
220
+
221
+ The reliability precedence is `INSUFFICIENT_CALIBRATION`, then `DISTRIBUTION_SHIFT_SUSPECTED`, then `WEAK_FIT`, then `TRUSTWORTHY`. Distribution-shift screening requires at least `baseline_regression_shift_min_points` current observations (default 5) and compares the current median residual with the walk-forward residual centre using a robust scale. It is an exploratory screening heuristic, not a formal drift test; a small current window cannot establish absence of drift. A `TRUSTWORTHY` status does not prove a physical model or equipment health, and downstream consumers should still inspect validation metrics and process context.
222
+
223
+ Relevant settings:
224
+ - `baseline_regression_nonlinear_improvement`: minimum relative holdout RMSE improvement required to select quadratic (default `0.15`).
225
+ - `baseline_regression_min_r_squared`: minimum holdout R-squared used to label fit quality (default `0.5`).
226
+ - `baseline_regression_variance_ratio_threshold`: high/low load residual robust-scale ratio that flags suspected heteroscedasticity (default `3.0`).
227
+ - `baseline_regression_prediction_interval_coverage`: target empirical prediction interval coverage (default `0.95`, must be between 0.5 and 1).
228
+ - `baseline_regression_interval_min_points`: minimum nearby calibration errors for local interval estimation (default `20`, at least `5`).
229
+ - `baseline_regression_shift_min_points`: minimum current observations required for residual-shift screening (default `5`, at least `3`).
230
+ - `baseline_regression_shift_z_threshold`: robust residual-shift score that marks suspected distribution shift (default `3.5`).
231
+
232
+ The current quadratic candidate is intentionally modest: it detects a simple curved relationship, not arbitrary nonlinear dynamics. Holdout quality depends on historical coverage and operating conditions; walk-forward validation better respects chronology, but serial dependence, changing operating regimes and distribution shift can still weaken calibration. Prediction intervals are not formal guarantees under those conditions. Validate model diagnostics with domain knowledge before using them operationally.
233
+
234
+
235
+ ### Longitudinal model monitoring
236
+
237
+ Use `ModelMonitor` to track model reliability transitions, validation metrics and observed prediction-interval calibration across successive calls to `analyze`. Monitoring is separate from the diagnostic engine: it does not retrain models, alter findings or persist data unless you explicitly provide a history path.
238
+
239
+ ```python
240
+ from historecon import DiagnosticConfig, DiagnosticEngine, ModelMonitor
241
+
242
+ engine = DiagnosticEngine(DiagnosticConfig(baseline_regression_enabled=True))
243
+ monitor = ModelMonitor("monitoring/model-history.jsonl")
244
+
245
+ report = engine.analyze(current_data, baseline_data=historical_data)
246
+ snapshots = monitor.record(report, run_id="daily-2026-12-06")
247
+
248
+ for snapshot in snapshots:
249
+ print(snapshot["tag"], snapshot["reliability_transition"])
250
+ print(snapshot["validation_metrics"])
251
+
252
+ latest = monitor.latest("PUMP_101", "RUNNING")
253
+ history = monitor.history(tag="PUMP_101")
254
+ ```
255
+
256
+ The JSON Lines history file is append-only and can be reused by a new `ModelMonitor` instance on a later process run. If no path is supplied, records are kept only in memory for that monitor instance. Model identity is the tag plus operating-mode key; separate operating modes are tracked independently.
257
+
258
+ Each snapshot records:
259
+ - Previous and current reliability status, whether it changed, and a transition label such as `TRUSTWORTHY -> WEAK_FIT`.
260
+ - Walk-forward RMSE, R-squared, prediction count and low/high-load residual robust scales.
261
+ - Prediction-interval target coverage and calibration status.
262
+ - Empirical interval coverage and mean interval width calculated from current observations for which an interval and observed value are both available.
263
+
264
+ Empirical coverage is measured on the current analysis window, not on the walk-forward calibration sample. It is descriptive and can be noisy for small windows; it is not a guarantee of future coverage. Missing interval evidence remains `None`, not zero. Persistent alert lifecycle is available through a separate append-only event log. Configure the alert path and the number of consecutive distinct runs required to open a distribution-shift alert:
265
+
266
+ ```python
267
+ monitor = ModelMonitor(
268
+ "monitoring/model-history.jsonl",
269
+ alert_path="monitoring/model-alert-events.jsonl",
270
+ distribution_shift_runs=3,
271
+ )
272
+
273
+ # Call after each analysis report has been recorded.
274
+ monitor.record(report, run_id="daily-2026-12-06")
275
+
276
+ for alert in monitor.alerts(status="OPEN"):
277
+ print(alert["alert_id"], alert["tag"], alert["rule"])
278
+
279
+ # Acknowledge without deleting the alert or its event history.
280
+ monitor.acknowledge_alert(
281
+ alert_id,
282
+ acknowledged_by="on-call-engineer",
283
+ note="Investigating process change",
284
+ )
285
+
286
+ # Current state and complete lifecycle history:
287
+ monitor.alerts()
288
+ monitor.alert_events(alert_id=alert_id)
289
+ ```
290
+
291
+ The initial rule opens one `PERSISTENT_DISTRIBUTION_SHIFT` alert per tag/operating-mode model after the configured number of consecutive distinct run IDs report `DISTRIBUTION_SHIFT_SUSPECTED`. Repeated evaluations of the same run ID do not advance the streak. An alert remains open until a subsequent recorded run for that model leaves the suspected-shift state; it then transitions to `RECOVERED`. Acknowledgement changes `OPEN` to `ACKNOWLEDGED` but does not suppress recovery tracking. A new shift after recovery opens a new alert episode.
292
+
293
+ The alert event log stores `OPENED`, `ACKNOWLEDGED` and `RECOVERED` events, while `alerts()` exposes the latest state. Acknowledgement returns `None` for unknown, recovered or already acknowledged alert IDs. Persistence is opt-in. This layer records alert events independently of delivery. Optional webhook adapters and a separate retry worker are documented below; detection itself never sends notifications.
294
+
295
+ ### Notification adapters and retry worker
296
+
297
+ Detection and alert lifecycle management never perform network requests. Configure vendor-specific adapters separately:
298
+
299
+ ```python
300
+ from historecon import (
301
+ ModelMonitor, NotificationDispatcher, NotificationRetryWorker,
302
+ SlackWebhookAdapter, TeamsWebhookAdapter,
303
+ )
304
+
305
+ monitor = ModelMonitor(
306
+ "monitoring/model-history.jsonl",
307
+ alert_path="monitoring/model-alert-events.jsonl",
308
+ distribution_shift_runs=3,
309
+ )
310
+ dispatcher = NotificationDispatcher(
311
+ adapters=[
312
+ SlackWebhookAdapter("https://hooks.slack.com/services/WORKSPACE/CHANNEL/TOKEN"),
313
+ TeamsWebhookAdapter("https://example.webhook.office.com/workflows/WORKFLOW/trigger"),
314
+ ],
315
+ delivery_path="monitoring/notification-deliveries.jsonl",
316
+ base_retry_seconds=30,
317
+ max_retry_seconds=3600,
318
+ max_attempts=8,
319
+ )
320
+ worker = NotificationRetryWorker(
321
+ dispatcher,
322
+ event_source=monitor.alert_events,
323
+ poll_interval_seconds=30,
324
+ )
325
+
326
+ # Detection records lifecycle events. It does not send messages.
327
+ monitor.record(report, run_id="daily-2026-12-06")
328
+
329
+ # Run once from a scheduler, or use run_forever in a dedicated worker process.
330
+ results = worker.run_once()
331
+ # worker.run_forever(stop_event=threading.Event())
332
+ ```
333
+
334
+ `SlackWebhookAdapter` formats events as Slack Block Kit messages. `TeamsWebhookAdapter` sends an Adaptive Card payload to a Microsoft Teams Workflows webhook endpoint configured to accept Adaptive Cards. `WebhookAdapter` remains available for generic JSON HTTP endpoints. All adapters use the event ID as an `Idempotency-Key`.
335
+
336
+ The dispatcher persists delivery attempts, failures, next-attempt timestamps and successful delivery state when `delivery_path` is supplied. Failed requests are retried with exponential backoff, capped by `max_retry_seconds`. `max_attempts` optionally moves exhausted deliveries to `GAVE_UP`; leave it as `None` for unbounded retries. `NotificationRetryWorker.run_once()` is scheduler-friendly; `run_forever()` provides a simple polling loop that can be stopped with a threading.Event-like object.
337
+
338
+ Delivery is at-least-once, not exactly-once. A receiver should deduplicate by idempotency key because a sender crash after remote acceptance but before local persistence can result in a retry. The retry ledger is append-only JSONL, but does not provide concurrent multi-process coordination, jitter, a dead-letter queue or exactly-once guarantees. Secure webhook URLs and credentials as secrets; do not commit them to source control.
339
+
340
+ ### Delivery health in the dashboard
341
+
342
+ Pass the dispatcher to the dashboard renderer to include current delivery states, adapter, attempt count, next retry time and last error:
343
+
344
+ ```python
345
+ monitor.render_dashboard(
346
+ "reports/model-health.html",
347
+ notification_dispatcher=dispatcher,
348
+ )
349
+ ```
350
+
351
+ The dashboard reports delivered, failed/retry-scheduled and exhausted deliveries. It is a snapshot of the dispatcher's current ledger, not a live view.
352
+
353
+ Alert JSONL persistence is append-only but is not safe for concurrent multi-process writers. Retention policies, distributed locking/coordination, scheduled notification delivery and automated remediation are not implemented. For concurrent notification delivery use the optional PostgreSQL store and its claim protocol; never share local JSONL files between writers.
354
+
355
+ ### Model Health Dashboard
356
+
357
+ Generate a dependency-free, self-contained HTML snapshot from the monitoring history:
358
+
359
+ ```python
360
+ from historecon import DashboardConfig, ModelMonitor
361
+
362
+ monitor = ModelMonitor("monitoring/model-history.jsonl")
363
+
364
+ # After recording one or more DiagnosticReport objects:
365
+ monitor.render_dashboard("reports/model-health.html")
366
+
367
+ # Or customise screening thresholds:
368
+ monitor.render_dashboard(
369
+ "reports/model-health.html",
370
+ config=DashboardConfig(
371
+ calibration_coverage_tolerance=0.05,
372
+ rmse_degradation_ratio=1.5,
373
+ distribution_shift_runs=3,
374
+ recent_runs=10,
375
+ ),
376
+ )
377
+ ```
378
+
379
+ The dashboard displays model reliability states, recent state transitions, walk-forward RMSE and R-squared trends, empirical prediction-interval coverage versus its target, interval width, and health warnings. It flags low or unavailable calibration, deteriorating RMSE relative to the first run in the displayed history window, and distribution shift that persists across a configurable number of consecutive runs. It also highlights coverage that is approaching the configured lower tolerance boundary.
380
+
381
+ `render_dashboard(records, output_path=None, config=None)` is also available as a standalone function. The renderer returns the HTML string and optionally writes it to disk. It uses only the Python standard library and embeds its CSS and SVG sparklines; it does not require a web server or JavaScript runtime. The dashboard is a point-in-time report, not a live application. Warning thresholds are screening heuristics and should be tuned to the model's operating context.
382
+
383
+ ## Pandas
384
+
385
+ ```python
386
+ import pandas as pd
387
+ from historecon import DiagnosticEngine
388
+
389
+ current_df = pd.read_csv("current.csv")
390
+ history_df = pd.read_csv("history.csv")
391
+ report = DiagnosticEngine().analyze(current_df, baseline_data=history_df)
392
+ ```
393
+
394
+ Pandas is imported only when a DataFrame is passed.
395
+
396
+ ## Findings
397
+
398
+ Each `Finding` contains a deterministic `finding_id`, diagnostic type and severity, affected tags, time window, evidence, confidence label, suggested owner, and recommended action.
399
+
400
+ Confidence describes strength of the observed pattern, not certainty about root cause.
401
+
402
+ ## Limitations
403
+
404
+ - Frozen detection needs suitable recorded values and enough observations. Interpolated data is excluded when `is_recorded=False`.
405
+ - A flat signal may be legitimate. Historecon reports a flatline pattern, not a confirmed failed sensor.
406
+ - Historical baseline quality depends on representative reference data and explicit quality labels.
407
+ - Mode-specific baselines require reliable `operating_mode` labels on both current and historical observations; labels are not inferred.
408
+ - Load-band baselines require a numeric `operating_load` value with consistent units on both current and historical observations. Missing load is treated as its own unsegmented group; it is never mixed with a numeric load band.
409
+ - Load bands do not model within-band trends, time-of-day seasonality or all process transitions.
410
+ - Stale detection needs a meaningful expected sampling interval.
411
+ - Cross-tag correlation indicates temporal coincidence, not causation.
412
+ - Source-specific status mappings must be configured by the user.
413
+ - Processing is currently in-memory. Large-scale Spark/Polars adapters and persistence integrations are future work.
414
+
415
+ ## Deployment boundary
416
+
417
+ PostgreSQL-backed notification dispatchers coordinate competing workers through per-delivery transaction locks and fresh database state. Configure stable adapter IDs and use the database event source directly. Delivery remains at-least-once; use receiver-side idempotency. Alert lifecycle writes still require one writer per stream. Local JSONL persistence is single-process only. See [deployment guide](docs/deployment.md).
418
+
419
+ ## Development
420
+
421
+ ```bash
422
+ python -m pip install -e ".[dev,pandas]"
423
+ pytest
424
+ ```
425
+
426
+ ## License
427
+
428
+ MIT. See [LICENSE](LICENSE).
429
+
430
+
431
+ ## Integration and deployment layer
432
+
433
+ The optional runtime layer adds environment-backed settings, JSON logs, lightweight
434
+ worker metrics, a Docker entry point, and PostgreSQL persistence. The core package
435
+ still has no mandatory runtime dependencies.
436
+
437
+ Install PostgreSQL support with:
438
+
439
+ ```bash
440
+ pip install "historecon[postgres]"
441
+ ```
442
+
443
+ The environment loader validates namespaced `HISTORECON_*` settings:
444
+
445
+ ```python
446
+ from historecon import HistoreconSettings, PostgresEventStore
447
+
448
+ settings = HistoreconSettings.from_env()
449
+ if settings.database_url:
450
+ event_store = PostgresEventStore(settings.database_url)
451
+ event_store.initialize() # run as a deployment migration step
452
+ ```
453
+
454
+ Pass the shared store to `AlertManager(event_store=event_store)` and
455
+ `NotificationDispatcher(..., delivery_store=event_store)` to persist alert
456
+ lifecycle events and notification delivery state in PostgreSQL. Existing JSONL
457
+ paths and constructor behaviour remain the default for local deployments.
458
+
459
+ For container deployments, configure
460
+ `HISTORECON_APP_FACTORY=your_package.worker:create_worker`. The factory receives
461
+ `HistoreconSettings` and must return a configured `NotificationRetryWorker`.
462
+ This keeps application-specific event sources and webhook secrets outside the
463
+ generic package. See [the deployment guide](docs/deployment.md) for Docker,
464
+ scheduled execution, configuration, and operational considerations.
465
+
466
+ PostgreSQL integration tests run against a PostgreSQL 16 service in GitHub Actions.