cogno-observability 0.1.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.
- cogno_observability-0.1.0/LICENSE +201 -0
- cogno_observability-0.1.0/PKG-INFO +135 -0
- cogno_observability-0.1.0/README.md +111 -0
- cogno_observability-0.1.0/cogno_observability/__init__.py +22 -0
- cogno_observability-0.1.0/cogno_observability/instrument.py +64 -0
- cogno_observability-0.1.0/cogno_observability/metrics.py +114 -0
- cogno_observability-0.1.0/cogno_observability/sink.py +158 -0
- cogno_observability-0.1.0/cogno_observability.egg-info/PKG-INFO +135 -0
- cogno_observability-0.1.0/cogno_observability.egg-info/SOURCES.txt +15 -0
- cogno_observability-0.1.0/cogno_observability.egg-info/dependency_links.txt +1 -0
- cogno_observability-0.1.0/cogno_observability.egg-info/requires.txt +14 -0
- cogno_observability-0.1.0/cogno_observability.egg-info/top_level.txt +1 -0
- cogno_observability-0.1.0/pyproject.toml +51 -0
- cogno_observability-0.1.0/setup.cfg +4 -0
- cogno_observability-0.1.0/tests/test_contract.py +51 -0
- cogno_observability-0.1.0/tests/test_instrument.py +43 -0
- cogno_observability-0.1.0/tests/test_sink.py +146 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Sudoers AI
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cogno-observability
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: SRE/Ops monitoring for the Cogno stack — Prometheus metrics sink + /metrics wiring + Grafana dashboards/alerts. Cross-tenant fleet health (NOT the tenant-facing Radar Tokens; NOT billing).
|
|
5
|
+
Author: Vinicius Vale
|
|
6
|
+
Maintainer: Sudoers AI
|
|
7
|
+
License: Apache-2.0
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: prometheus-client>=0.20
|
|
12
|
+
Provides-Extra: http
|
|
13
|
+
Requires-Dist: prometheus-fastapi-instrumentator>=7.0; extra == "http"
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
16
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
|
|
17
|
+
Requires-Dist: pytest-cov>=5.0; extra == "dev"
|
|
18
|
+
Requires-Dist: prometheus-fastapi-instrumentator>=7.0; extra == "dev"
|
|
19
|
+
Requires-Dist: fastapi>=0.110; extra == "dev"
|
|
20
|
+
Requires-Dist: httpx>=0.27; extra == "dev"
|
|
21
|
+
Requires-Dist: ruff>=0.5; extra == "dev"
|
|
22
|
+
Requires-Dist: mypy>=1.8; extra == "dev"
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# cogno-observability
|
|
26
|
+
|
|
27
|
+
**SRE/Ops monitoring for the [Cogno](https://github.com/sudoers-ai/cogno-anima) stack** — a Prometheus metrics sink + `/metrics` wiring + Grafana dashboards/alerts, plus a one-login deploy stack for metrics **and** live logs.
|
|
28
|
+
|
|
29
|
+
Where [`cogno-anima`](https://github.com/sudoers-ai/cogno-anima) is the *mind* and [`cogno-homeo`](https://github.com/sudoers-ai/cogno-homeo) keeps the calls *alive*, `cogno-observability` is the **operator's eyes** on the running fleet — how many turns, how fast, how much they cost, where they fail. It attaches to the host from *outside* its cognition, so the host never imports `prometheus_client`.
|
|
30
|
+
|
|
31
|
+
> Status: **alpha** — metrics sink + `/metrics` wiring + deploy stack + unit/contract suite in place.
|
|
32
|
+
|
|
33
|
+
SRE/Ops monitoring is the *operator-facing* pillar — cross-tenant fleet health — and is
|
|
34
|
+
deliberately **separate** from two other consumers of the same turn data:
|
|
35
|
+
|
|
36
|
+
| Surface | Audience | This repo? |
|
|
37
|
+
|---|---|---|
|
|
38
|
+
| **Fleet monitoring** (Prometheus/Grafana, cross-tenant) | operator / SRE | ✅ **yes** |
|
|
39
|
+
| **Radar Tokens** (per-tenant usage, from the `token_ledger`) | the tenant/customer | ❌ cogno-ui |
|
|
40
|
+
| **Billing / BudgetGuard** (quota, spend) | the platform | ❌ cogno-host + cogno-meter |
|
|
41
|
+
|
|
42
|
+
## Why a separate repo
|
|
43
|
+
|
|
44
|
+
The house rule is **libs emit, host configures** — and the host stays **prometheus-agnostic**. It
|
|
45
|
+
emits one `TurnEvent` per turn to an injected `MetricsSink` and exposes an `instrument(app)` hook;
|
|
46
|
+
it never imports `prometheus_client`. This package fills both seams, so the Prometheus dependency,
|
|
47
|
+
the metric catalog, and the dashboards live here — swappable, versioned independently, and absent
|
|
48
|
+
from a deployment that doesn't want them.
|
|
49
|
+
|
|
50
|
+
## Logs ≠ metrics
|
|
51
|
+
|
|
52
|
+
Two different pipelines. **Logs** (host `configure_logging` → stdout → Loki/ELK) answer *"what
|
|
53
|
+
happened in this turn?"* and may carry high-cardinality `tenant`/`identity`/`session`. **Metrics**
|
|
54
|
+
(this repo) answer *"how is the fleet doing?"* — aggregate series with **low-cardinality labels
|
|
55
|
+
only**. `session_id`/`identity_id` are **never** Prometheus labels (they'd blow up the TSDB); use
|
|
56
|
+
logs for per-turn tracing. `tenant` is opt-in and capped (`PrometheusMetricsSink(tenant_label=True)`).
|
|
57
|
+
|
|
58
|
+
## Install
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pip install cogno-observability # core (prometheus-client)
|
|
62
|
+
pip install "cogno-observability[http]" # + per-route HTTP RED metrics (fastapi instrumentator)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Wire it into the host
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from cogno_host.api.pg_app import create_pg_app
|
|
69
|
+
from cogno_observability import PrometheusMetricsSink, attach
|
|
70
|
+
|
|
71
|
+
app = create_pg_app(
|
|
72
|
+
dsn, auth=admin,
|
|
73
|
+
metrics_sink=PrometheusMetricsSink(), # per-turn TurnEvent → Prometheus series
|
|
74
|
+
instrument=attach, # mounts /metrics + HTTP instrumentation
|
|
75
|
+
)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
With neither argument the host runs exactly as before (no-op sink, no `/metrics`).
|
|
79
|
+
|
|
80
|
+
## Metrics
|
|
81
|
+
|
|
82
|
+
| Metric | Type | Labels | Meaning |
|
|
83
|
+
|---|---|---|---|
|
|
84
|
+
| `cogno_turns_total` | counter | route, stop_reason, ok, blocked, cache_hit | turn outcomes |
|
|
85
|
+
| `cogno_turn_errors_total` | counter | error | unhandled exceptions (by class) |
|
|
86
|
+
| `cogno_turn_duration_seconds` | histogram | route | end-to-end latency |
|
|
87
|
+
| `cogno_stage_duration_seconds` | histogram | stage | per cognitive-stage latency |
|
|
88
|
+
| `cogno_stage_tokens_total` | counter | stage, model, direction | tokens (in/out/embedding) |
|
|
89
|
+
| `cogno_cost_usd_total` | counter | — | provider spend (0 for local) |
|
|
90
|
+
| `cogno_drift_score` | histogram | — | cumulative drift distribution |
|
|
91
|
+
| `cogno_drift_actions_total` | counter | action | drift-triggered actions |
|
|
92
|
+
| `cogno_tool_calls_total` / `_failures_total` | counter | — | EGO tool calls / failures |
|
|
93
|
+
| `cogno_failovers_total`, `cogno_self_corrections_total`, `cogno_handoffs_total` | counter | — | reliability |
|
|
94
|
+
| `cogno_blocked_total` | counter | stop_reason | safety/quota/PII blocks |
|
|
95
|
+
|
|
96
|
+
Plus HTTP RED metrics (`http_request_*`) from the instrumentator.
|
|
97
|
+
|
|
98
|
+
## Multi-worker
|
|
99
|
+
|
|
100
|
+
Each uvicorn/gunicorn worker has its own registry. Set `PROMETHEUS_MULTIPROC_DIR` to a shared
|
|
101
|
+
(empty at boot) dir and `attach` will reconcile across workers via `MultiProcessCollector` at scrape
|
|
102
|
+
time. Without it, single-process mode is used.
|
|
103
|
+
|
|
104
|
+
## Ops assets (`ops/`)
|
|
105
|
+
|
|
106
|
+
- `alerts/cogno_rules.yml` — Prometheus recording + alerting rules.
|
|
107
|
+
- `dashboards/cogno_overview.json` — Grafana dashboard (import, pick your Prometheus datasource).
|
|
108
|
+
- `dashboards/cogno_logs.json` — Grafana dashboard for live logs (Loki).
|
|
109
|
+
- `prometheus-scrape.example.yml` — scrape config / ServiceMonitor example.
|
|
110
|
+
- `SLOs.md` — starting SLOs + a metric→runbook map.
|
|
111
|
+
|
|
112
|
+
## Deploy — one Grafana login for metrics + logs
|
|
113
|
+
|
|
114
|
+
`deploy/` is a docker-compose stack (Prometheus + Loki + Promtail + Grafana) that watches an
|
|
115
|
+
existing host and gives you **one Grafana login** to follow it live — metrics and near-real-time
|
|
116
|
+
logs on the same pane. See [`deploy/README.md`](deploy/README.md).
|
|
117
|
+
|
|
118
|
+
## Host integration
|
|
119
|
+
|
|
120
|
+
The host exposes two seams (`metrics_sink=` + `instrument(app)`) and stays prometheus-agnostic;
|
|
121
|
+
this library fills them. See [`docs/HOST_INTEGRATION.md`](docs/HOST_INTEGRATION.md).
|
|
122
|
+
|
|
123
|
+
## The Cogno ecosystem
|
|
124
|
+
|
|
125
|
+
`cogno-observability` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
|
|
126
|
+
small, composable, Apache-2.0 libraries that together form a complete conversational-agent
|
|
127
|
+
platform. Each library owns a single concern and stays infra-agnostic; a **host** assembles them
|
|
128
|
+
into a running agent:
|
|
129
|
+
|
|
130
|
+

|
|
131
|
+
|
|
132
|
+
The open-source libraries are the organs; the **host is the body** that joins them. Our reference
|
|
133
|
+
host — `cogno-host`, with its `cogno-ui` dashboard — is the private product layer, but it holds no
|
|
134
|
+
special powers: everything it does rides on the public seams documented in each library's
|
|
135
|
+
`docs/HOST_INTEGRATION.md`.
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# cogno-observability
|
|
2
|
+
|
|
3
|
+
**SRE/Ops monitoring for the [Cogno](https://github.com/sudoers-ai/cogno-anima) stack** — a Prometheus metrics sink + `/metrics` wiring + Grafana dashboards/alerts, plus a one-login deploy stack for metrics **and** live logs.
|
|
4
|
+
|
|
5
|
+
Where [`cogno-anima`](https://github.com/sudoers-ai/cogno-anima) is the *mind* and [`cogno-homeo`](https://github.com/sudoers-ai/cogno-homeo) keeps the calls *alive*, `cogno-observability` is the **operator's eyes** on the running fleet — how many turns, how fast, how much they cost, where they fail. It attaches to the host from *outside* its cognition, so the host never imports `prometheus_client`.
|
|
6
|
+
|
|
7
|
+
> Status: **alpha** — metrics sink + `/metrics` wiring + deploy stack + unit/contract suite in place.
|
|
8
|
+
|
|
9
|
+
SRE/Ops monitoring is the *operator-facing* pillar — cross-tenant fleet health — and is
|
|
10
|
+
deliberately **separate** from two other consumers of the same turn data:
|
|
11
|
+
|
|
12
|
+
| Surface | Audience | This repo? |
|
|
13
|
+
|---|---|---|
|
|
14
|
+
| **Fleet monitoring** (Prometheus/Grafana, cross-tenant) | operator / SRE | ✅ **yes** |
|
|
15
|
+
| **Radar Tokens** (per-tenant usage, from the `token_ledger`) | the tenant/customer | ❌ cogno-ui |
|
|
16
|
+
| **Billing / BudgetGuard** (quota, spend) | the platform | ❌ cogno-host + cogno-meter |
|
|
17
|
+
|
|
18
|
+
## Why a separate repo
|
|
19
|
+
|
|
20
|
+
The house rule is **libs emit, host configures** — and the host stays **prometheus-agnostic**. It
|
|
21
|
+
emits one `TurnEvent` per turn to an injected `MetricsSink` and exposes an `instrument(app)` hook;
|
|
22
|
+
it never imports `prometheus_client`. This package fills both seams, so the Prometheus dependency,
|
|
23
|
+
the metric catalog, and the dashboards live here — swappable, versioned independently, and absent
|
|
24
|
+
from a deployment that doesn't want them.
|
|
25
|
+
|
|
26
|
+
## Logs ≠ metrics
|
|
27
|
+
|
|
28
|
+
Two different pipelines. **Logs** (host `configure_logging` → stdout → Loki/ELK) answer *"what
|
|
29
|
+
happened in this turn?"* and may carry high-cardinality `tenant`/`identity`/`session`. **Metrics**
|
|
30
|
+
(this repo) answer *"how is the fleet doing?"* — aggregate series with **low-cardinality labels
|
|
31
|
+
only**. `session_id`/`identity_id` are **never** Prometheus labels (they'd blow up the TSDB); use
|
|
32
|
+
logs for per-turn tracing. `tenant` is opt-in and capped (`PrometheusMetricsSink(tenant_label=True)`).
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install cogno-observability # core (prometheus-client)
|
|
38
|
+
pip install "cogno-observability[http]" # + per-route HTTP RED metrics (fastapi instrumentator)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Wire it into the host
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from cogno_host.api.pg_app import create_pg_app
|
|
45
|
+
from cogno_observability import PrometheusMetricsSink, attach
|
|
46
|
+
|
|
47
|
+
app = create_pg_app(
|
|
48
|
+
dsn, auth=admin,
|
|
49
|
+
metrics_sink=PrometheusMetricsSink(), # per-turn TurnEvent → Prometheus series
|
|
50
|
+
instrument=attach, # mounts /metrics + HTTP instrumentation
|
|
51
|
+
)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
With neither argument the host runs exactly as before (no-op sink, no `/metrics`).
|
|
55
|
+
|
|
56
|
+
## Metrics
|
|
57
|
+
|
|
58
|
+
| Metric | Type | Labels | Meaning |
|
|
59
|
+
|---|---|---|---|
|
|
60
|
+
| `cogno_turns_total` | counter | route, stop_reason, ok, blocked, cache_hit | turn outcomes |
|
|
61
|
+
| `cogno_turn_errors_total` | counter | error | unhandled exceptions (by class) |
|
|
62
|
+
| `cogno_turn_duration_seconds` | histogram | route | end-to-end latency |
|
|
63
|
+
| `cogno_stage_duration_seconds` | histogram | stage | per cognitive-stage latency |
|
|
64
|
+
| `cogno_stage_tokens_total` | counter | stage, model, direction | tokens (in/out/embedding) |
|
|
65
|
+
| `cogno_cost_usd_total` | counter | — | provider spend (0 for local) |
|
|
66
|
+
| `cogno_drift_score` | histogram | — | cumulative drift distribution |
|
|
67
|
+
| `cogno_drift_actions_total` | counter | action | drift-triggered actions |
|
|
68
|
+
| `cogno_tool_calls_total` / `_failures_total` | counter | — | EGO tool calls / failures |
|
|
69
|
+
| `cogno_failovers_total`, `cogno_self_corrections_total`, `cogno_handoffs_total` | counter | — | reliability |
|
|
70
|
+
| `cogno_blocked_total` | counter | stop_reason | safety/quota/PII blocks |
|
|
71
|
+
|
|
72
|
+
Plus HTTP RED metrics (`http_request_*`) from the instrumentator.
|
|
73
|
+
|
|
74
|
+
## Multi-worker
|
|
75
|
+
|
|
76
|
+
Each uvicorn/gunicorn worker has its own registry. Set `PROMETHEUS_MULTIPROC_DIR` to a shared
|
|
77
|
+
(empty at boot) dir and `attach` will reconcile across workers via `MultiProcessCollector` at scrape
|
|
78
|
+
time. Without it, single-process mode is used.
|
|
79
|
+
|
|
80
|
+
## Ops assets (`ops/`)
|
|
81
|
+
|
|
82
|
+
- `alerts/cogno_rules.yml` — Prometheus recording + alerting rules.
|
|
83
|
+
- `dashboards/cogno_overview.json` — Grafana dashboard (import, pick your Prometheus datasource).
|
|
84
|
+
- `dashboards/cogno_logs.json` — Grafana dashboard for live logs (Loki).
|
|
85
|
+
- `prometheus-scrape.example.yml` — scrape config / ServiceMonitor example.
|
|
86
|
+
- `SLOs.md` — starting SLOs + a metric→runbook map.
|
|
87
|
+
|
|
88
|
+
## Deploy — one Grafana login for metrics + logs
|
|
89
|
+
|
|
90
|
+
`deploy/` is a docker-compose stack (Prometheus + Loki + Promtail + Grafana) that watches an
|
|
91
|
+
existing host and gives you **one Grafana login** to follow it live — metrics and near-real-time
|
|
92
|
+
logs on the same pane. See [`deploy/README.md`](deploy/README.md).
|
|
93
|
+
|
|
94
|
+
## Host integration
|
|
95
|
+
|
|
96
|
+
The host exposes two seams (`metrics_sink=` + `instrument(app)`) and stays prometheus-agnostic;
|
|
97
|
+
this library fills them. See [`docs/HOST_INTEGRATION.md`](docs/HOST_INTEGRATION.md).
|
|
98
|
+
|
|
99
|
+
## The Cogno ecosystem
|
|
100
|
+
|
|
101
|
+
`cogno-observability` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
|
|
102
|
+
small, composable, Apache-2.0 libraries that together form a complete conversational-agent
|
|
103
|
+
platform. Each library owns a single concern and stays infra-agnostic; a **host** assembles them
|
|
104
|
+
into a running agent:
|
|
105
|
+
|
|
106
|
+

|
|
107
|
+
|
|
108
|
+
The open-source libraries are the organs; the **host is the body** that joins them. Our reference
|
|
109
|
+
host — `cogno-host`, with its `cogno-ui` dashboard — is the private product layer, but it holds no
|
|
110
|
+
special powers: everything it does rides on the public seams documented in each library's
|
|
111
|
+
`docs/HOST_INTEGRATION.md`.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""cogno-observability — SRE/Ops monitoring for the Cogno stack.
|
|
2
|
+
|
|
3
|
+
The **operator-facing** half of observability (cross-tenant fleet health), separate from the
|
|
4
|
+
**tenant-facing** Radar Tokens in cogno-ui and from billing. The host stays prometheus-agnostic
|
|
5
|
+
and exposes two seams; this package fills them:
|
|
6
|
+
|
|
7
|
+
* :class:`PrometheusMetricsSink` — implements the host's ``MetricsSink`` (``record(TurnEvent)``),
|
|
8
|
+
turning each turn into Prometheus time-series.
|
|
9
|
+
* :func:`attach` — the ``instrument(app)`` hook that mounts ``/metrics`` + HTTP RED metrics.
|
|
10
|
+
|
|
11
|
+
from cogno_observability import PrometheusMetricsSink, attach
|
|
12
|
+
app = create_pg_app(dsn, auth=admin, metrics_sink=PrometheusMetricsSink(), instrument=attach)
|
|
13
|
+
|
|
14
|
+
Grafana dashboards + Prometheus alert/recording rules live under ``ops/``.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from cogno_observability.instrument import attach
|
|
18
|
+
from cogno_observability.metrics import Metrics
|
|
19
|
+
from cogno_observability.sink import PrometheusMetricsSink, TurnEventLike
|
|
20
|
+
|
|
21
|
+
__all__ = ["PrometheusMetricsSink", "attach", "Metrics", "TurnEventLike"]
|
|
22
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""``attach(app)`` — the host's ``instrument`` hook: mount ``/metrics`` + HTTP RED instrumentation.
|
|
2
|
+
|
|
3
|
+
Passed to ``create_pg_app(..., instrument=attach)``. The host calls it right after building the
|
|
4
|
+
FastAPI app (before routers), so it wraps every route. Keeping this here — not in the host — is
|
|
5
|
+
the whole point of the split: the host never imports ``prometheus_client``.
|
|
6
|
+
|
|
7
|
+
**Multiprocess (N uvicorn/gunicorn workers).** Each worker has its own in-process registry, so a
|
|
8
|
+
naive ``/metrics`` would report only the scraped worker's slice. When ``PROMETHEUS_MULTIPROC_DIR``
|
|
9
|
+
is set, prometheus_client writes counters to that shared dir and the exposition endpoint reconciles
|
|
10
|
+
across workers via ``MultiProcessCollector``. Set the env var and ensure the dir exists/empty at
|
|
11
|
+
boot (per the prometheus_client docs). Without it, single-process mode is used (dev / one worker).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
import os
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
log = logging.getLogger("cogno_observability.instrument")
|
|
21
|
+
|
|
22
|
+
_EXCLUDED = ("/metrics", "/health")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def attach(app: Any, *, metrics_path: str = "/metrics", instrument_http: bool = True) -> None:
|
|
26
|
+
"""Mount ``metrics_path`` on ``app`` and (optionally) add per-route HTTP RED metrics.
|
|
27
|
+
|
|
28
|
+
Best-effort and idempotent-ish: a missing optional dep degrades gracefully (business metrics
|
|
29
|
+
still work; only the HTTP layer is skipped)."""
|
|
30
|
+
if instrument_http:
|
|
31
|
+
try:
|
|
32
|
+
from prometheus_fastapi_instrumentator import Instrumentator
|
|
33
|
+
Instrumentator(
|
|
34
|
+
should_group_status_codes=False,
|
|
35
|
+
should_ignore_untemplated=True,
|
|
36
|
+
excluded_handlers=list(_EXCLUDED),
|
|
37
|
+
).instrument(app) # records default http_request_* to the global REGISTRY
|
|
38
|
+
log.info("event=http_instrumented")
|
|
39
|
+
except ImportError:
|
|
40
|
+
log.warning("event=http_instrument_skipped reason=prometheus-fastapi-instrumentator "
|
|
41
|
+
"not installed (pip install 'cogno-observability[http]')")
|
|
42
|
+
|
|
43
|
+
app.mount(metrics_path, _metrics_asgi_app())
|
|
44
|
+
log.info("event=metrics_mounted path=%s multiprocess=%s",
|
|
45
|
+
metrics_path, bool(os.environ.get("PROMETHEUS_MULTIPROC_DIR")))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _metrics_asgi_app() -> Any:
|
|
49
|
+
"""Build the ``/metrics`` ASGI app — a multiprocess-reconciling registry when configured,
|
|
50
|
+
else the default global registry."""
|
|
51
|
+
from prometheus_client import make_asgi_app
|
|
52
|
+
mpdir = os.environ.get("PROMETHEUS_MULTIPROC_DIR")
|
|
53
|
+
if mpdir:
|
|
54
|
+
# prometheus_client requires the dir to EXIST and be emptied at process start (stale files
|
|
55
|
+
# from a previous run would be summed into the exposition). We can't empty it here safely
|
|
56
|
+
# (sibling workers may already be writing), but we can catch the common misconfiguration.
|
|
57
|
+
if not os.path.isdir(mpdir):
|
|
58
|
+
log.warning("event=multiproc_dir_missing dir=%s — /metrics will under-report; create it "
|
|
59
|
+
"and empty it at boot (per PROMETHEUS_MULTIPROC_DIR docs)", mpdir)
|
|
60
|
+
from prometheus_client import CollectorRegistry, multiprocess
|
|
61
|
+
registry = CollectorRegistry()
|
|
62
|
+
multiprocess.MultiProcessCollector(registry)
|
|
63
|
+
return make_asgi_app(registry=registry)
|
|
64
|
+
return make_asgi_app()
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Prometheus metric definitions for the Cogno pipeline (business/SRE layer).
|
|
2
|
+
|
|
3
|
+
These live in a **separate Ops repo** (not cogno-host, not cogno-ui): the host stays
|
|
4
|
+
prometheus-agnostic and only emits a ``TurnEvent`` per turn to an injected ``MetricsSink``; this
|
|
5
|
+
module is where those events become time-series scraped into Grafana.
|
|
6
|
+
|
|
7
|
+
**Cardinality discipline (the cardinal rule of Prometheus):** every label here is a *bounded*
|
|
8
|
+
set — ``route`` (~4), ``stop_reason`` (~8), ``stage`` (~6), ``model`` (the deployment's catalog),
|
|
9
|
+
``direction`` (3), ``action`` (4), ``error`` (exception class names). High-cardinality identifiers
|
|
10
|
+
(``session_id`` / ``identity_id``) are **deliberately absent** — they belong in logs (Loki), never
|
|
11
|
+
as labels, or they blow up the TSDB. ``tenant`` is opt-in and capped (see :class:`sink` config)
|
|
12
|
+
because a large multi-tenant fleet is still unbounded.
|
|
13
|
+
|
|
14
|
+
Adapted from the parent monolith's ``cogno/core/metrics.py``, but fed off the decomposed host's
|
|
15
|
+
``TurnEvent`` DTO instead of reaching into a ``PipelineContext`` (whose field names differ).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from typing import Any, Callable
|
|
21
|
+
|
|
22
|
+
from prometheus_client import REGISTRY, CollectorRegistry, Counter, Histogram
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _get_or_create(reg: CollectorRegistry, name: str, factory: Callable[[], Any]) -> Any:
|
|
26
|
+
"""Create a metric, or return the one already registered under ``name`` on ``reg``.
|
|
27
|
+
|
|
28
|
+
prometheus_client raises ``ValueError: Duplicated timeseries`` if a name is registered twice on
|
|
29
|
+
the same registry, so constructing a second ``Metrics``/``PrometheusMetricsSink`` on the default
|
|
30
|
+
``REGISTRY`` (gunicorn --preload + fork, an app factory reused across tests, a hot reload) would
|
|
31
|
+
crash at boot. Reuse the existing collector instead — two sinks on one registry then share the
|
|
32
|
+
same series, which is exactly right for a process-global registry."""
|
|
33
|
+
try:
|
|
34
|
+
return factory()
|
|
35
|
+
except ValueError:
|
|
36
|
+
existing = getattr(reg, "_names_to_collectors", {}).get(name)
|
|
37
|
+
if existing is None:
|
|
38
|
+
raise
|
|
39
|
+
return existing
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# Latency buckets (seconds) tuned for LLM turns: sub-second cache hits → multi-minute agent loops.
|
|
43
|
+
_TURN_BUCKETS = (0.25, 0.5, 1, 2, 5, 10, 20, 30, 60, 120, 300)
|
|
44
|
+
_STAGE_BUCKETS = (0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 30, 60)
|
|
45
|
+
_DRIFT_BUCKETS = (0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Metrics:
|
|
49
|
+
"""The Cogno metric set, bound to one registry (default: the global one).
|
|
50
|
+
|
|
51
|
+
Held on an instance rather than module globals so tests get a fresh registry each time and a
|
|
52
|
+
multiprocess deployment can pass its own. All names are prefixed ``cogno_`` and carry a HELP
|
|
53
|
+
string (Grafana/alerts reference them by name)."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, registry: CollectorRegistry | None = None) -> None:
|
|
56
|
+
# NB: prometheus_client treats ``registry=None`` as "register nowhere" (not "the default"),
|
|
57
|
+
# so resolve None to the global REGISTRY explicitly.
|
|
58
|
+
reg = registry if registry is not None else REGISTRY
|
|
59
|
+
|
|
60
|
+
def counter(name: str, doc: str, labels: list[str] | None = None) -> Any:
|
|
61
|
+
return _get_or_create(reg, name, lambda: Counter(
|
|
62
|
+
name, doc, labels or [], registry=reg))
|
|
63
|
+
|
|
64
|
+
def histogram(name: str, doc: str, buckets: tuple,
|
|
65
|
+
labels: list[str] | None = None) -> Any:
|
|
66
|
+
return _get_or_create(reg, name, lambda: Histogram(
|
|
67
|
+
name, doc, labels or [], buckets=buckets, registry=reg))
|
|
68
|
+
|
|
69
|
+
# ── turn outcomes ────────────────────────────────────────────────────────────────
|
|
70
|
+
self.turns_total = counter(
|
|
71
|
+
"cogno_turns_total", "Pipeline turns by outcome",
|
|
72
|
+
["route", "stop_reason", "ok", "blocked", "cache_hit"])
|
|
73
|
+
self.turn_errors_total = counter(
|
|
74
|
+
"cogno_turn_errors_total", "Turns that raised an unhandled exception", ["error"])
|
|
75
|
+
self.turn_duration_seconds = histogram(
|
|
76
|
+
"cogno_turn_duration_seconds", "End-to-end turn latency", _TURN_BUCKETS, ["route"])
|
|
77
|
+
|
|
78
|
+
# ── per-stage cost ───────────────────────────────────────────────────────────────
|
|
79
|
+
self.stage_duration_seconds = histogram(
|
|
80
|
+
"cogno_stage_duration_seconds", "Per cognitive-stage latency", _STAGE_BUCKETS, ["stage"])
|
|
81
|
+
self.stage_tokens_total = counter(
|
|
82
|
+
"cogno_stage_tokens_total", "Tokens consumed per stage/model",
|
|
83
|
+
["stage", "model", "direction"]) # direction: in|out|embedding
|
|
84
|
+
self.cost_usd_total = counter(
|
|
85
|
+
"cogno_cost_usd_total", "Provider cost in USD (0 for local models)")
|
|
86
|
+
|
|
87
|
+
# ── quality / reliability signals ────────────────────────────────────────────────
|
|
88
|
+
self.drift_score = histogram(
|
|
89
|
+
"cogno_drift_score", "Cumulative drift score distribution", _DRIFT_BUCKETS)
|
|
90
|
+
self.drift_actions_total = counter(
|
|
91
|
+
"cogno_drift_actions_total", "Drift-triggered actions",
|
|
92
|
+
["action"]) # none|warn|ask_user|self_correct
|
|
93
|
+
self.tool_calls_total = counter(
|
|
94
|
+
"cogno_tool_calls_total", "EGO tool executions")
|
|
95
|
+
self.tool_failures_total = counter(
|
|
96
|
+
"cogno_tool_failures_total", "EGO tool executions that returned ok=False")
|
|
97
|
+
self.failovers_total = counter(
|
|
98
|
+
"cogno_failovers_total", "LLM backend failover events")
|
|
99
|
+
self.self_corrections_total = counter(
|
|
100
|
+
"cogno_self_corrections_total", "EGO↔SUPEREGO correction retries")
|
|
101
|
+
self.handoffs_total = counter(
|
|
102
|
+
"cogno_handoffs_total", "Turns escalated to a human handoff")
|
|
103
|
+
|
|
104
|
+
# ── protection nets (the anti-fabrication layers; see cogno-host grounding.py /
|
|
105
|
+
# provenance.py) — a rising rate = a model/vertical regressing upstream ──────────
|
|
106
|
+
self.grounding_rewrites_total = counter(
|
|
107
|
+
"cogno_grounding_rewrites_total",
|
|
108
|
+
"Replies rewritten by the grounding backstop, by rule; repaired=true means the "
|
|
109
|
+
"repair re-step delivered the real answer", ["rule", "repaired"])
|
|
110
|
+
self.provenance_refusals_total = counter(
|
|
111
|
+
"cogno_provenance_refusals_total",
|
|
112
|
+
"Stale-id writes refused by the id-provenance guard (absorbed in the EGO loop)")
|
|
113
|
+
self.blocked_total = counter(
|
|
114
|
+
"cogno_blocked_total", "Turns blocked (safety/quota/PII)", ["stop_reason"])
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""``PrometheusMetricsSink`` — translate a host ``TurnEvent`` into Prometheus time-series.
|
|
2
|
+
|
|
3
|
+
This is the concrete implementation of the host's ``MetricsSink`` protocol (``record(event)``).
|
|
4
|
+
It is **duck-typed** against the event — it reads attributes off it and never imports
|
|
5
|
+
``cogno_host``, so the Ops layer stays decoupled from the product repo (any host emitting the same
|
|
6
|
+
``TurnEvent`` shape is observable). The host injects it:
|
|
7
|
+
|
|
8
|
+
from cogno_observability import PrometheusMetricsSink, attach
|
|
9
|
+
app = create_pg_app(dsn, auth=admin,
|
|
10
|
+
metrics_sink=PrometheusMetricsSink(), instrument=attach)
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
from typing import Any, Optional, Protocol, runtime_checkable
|
|
17
|
+
|
|
18
|
+
from prometheus_client import CollectorRegistry
|
|
19
|
+
|
|
20
|
+
from cogno_observability.metrics import Metrics, _get_or_create
|
|
21
|
+
|
|
22
|
+
log = logging.getLogger("cogno_observability.sink")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@runtime_checkable
|
|
26
|
+
class TurnEventLike(Protocol):
|
|
27
|
+
"""The subset of the host's ``TurnEvent`` this sink reads (documentation + typing only)."""
|
|
28
|
+
|
|
29
|
+
tenant_id: str
|
|
30
|
+
route: str
|
|
31
|
+
stop_reason: str
|
|
32
|
+
total_tokens: int
|
|
33
|
+
elapsed_ms: float
|
|
34
|
+
cache_hit: bool
|
|
35
|
+
blocked: bool
|
|
36
|
+
ok: bool
|
|
37
|
+
error: str
|
|
38
|
+
cost_usd: float
|
|
39
|
+
drift_cumulative: float
|
|
40
|
+
drift_action: str
|
|
41
|
+
tool_calls: int
|
|
42
|
+
tool_failures: int
|
|
43
|
+
failover_count: int
|
|
44
|
+
correction_count: int
|
|
45
|
+
handoff: bool
|
|
46
|
+
stages: list
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _b(v: Any) -> str:
|
|
50
|
+
"""Prometheus label values must be strings — normalize a bool to a stable lowercase token."""
|
|
51
|
+
return "true" if bool(v) else "false"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class PrometheusMetricsSink:
|
|
55
|
+
"""A ``MetricsSink`` that records each turn to Prometheus counters/histograms.
|
|
56
|
+
|
|
57
|
+
``record`` is **best-effort**: monitoring must never break a turn, so any error while recording
|
|
58
|
+
is swallowed with a warning (the parent did the same). Set ``tenant_label=True`` ONLY on a
|
|
59
|
+
small/bounded fleet — it adds a ``tenant`` label to the turn counter (unbounded tenants would
|
|
60
|
+
explode cardinality; off by default)."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, *, registry: Optional[CollectorRegistry] = None,
|
|
63
|
+
tenant_label: bool = False) -> None:
|
|
64
|
+
self._m = Metrics(registry)
|
|
65
|
+
self._tenant_label = tenant_label
|
|
66
|
+
if tenant_label:
|
|
67
|
+
# A separate, opt-in counter carrying the tenant dimension (kept off the main
|
|
68
|
+
# counters so their cardinality stays flat). ``registry=None`` → the global REGISTRY;
|
|
69
|
+
# get-or-create so a second sink on that registry reuses it instead of crashing.
|
|
70
|
+
from prometheus_client import REGISTRY, Counter
|
|
71
|
+
reg = registry if registry is not None else REGISTRY
|
|
72
|
+
self._turns_by_tenant = _get_or_create(
|
|
73
|
+
reg, "cogno_turns_by_tenant_total", lambda: Counter(
|
|
74
|
+
"cogno_turns_by_tenant_total", "Turns per tenant (bounded fleets only)",
|
|
75
|
+
["tenant", "ok"], registry=reg))
|
|
76
|
+
|
|
77
|
+
def record(self, event: TurnEventLike) -> None:
|
|
78
|
+
try:
|
|
79
|
+
self._record(event)
|
|
80
|
+
except Exception as exc: # noqa: BLE001 — observability must not break the turn
|
|
81
|
+
log.warning("event=metrics_record_failed error=%s", exc)
|
|
82
|
+
|
|
83
|
+
def _record(self, e: Any) -> None:
|
|
84
|
+
m = self._m
|
|
85
|
+
route = getattr(e, "route", "") or "none"
|
|
86
|
+
stop_reason = getattr(e, "stop_reason", "") or "completed"
|
|
87
|
+
ok = getattr(e, "ok", True)
|
|
88
|
+
blocked = getattr(e, "blocked", False)
|
|
89
|
+
cache_hit = getattr(e, "cache_hit", False)
|
|
90
|
+
|
|
91
|
+
m.turns_total.labels(route=route, stop_reason=stop_reason, ok=_b(ok),
|
|
92
|
+
blocked=_b(blocked), cache_hit=_b(cache_hit)).inc()
|
|
93
|
+
if self._tenant_label:
|
|
94
|
+
self._turns_by_tenant.labels(tenant=getattr(e, "tenant_id", "") or "unknown",
|
|
95
|
+
ok=_b(ok)).inc()
|
|
96
|
+
|
|
97
|
+
if not ok:
|
|
98
|
+
m.turn_errors_total.labels(error=getattr(e, "error", "") or "unknown").inc()
|
|
99
|
+
if blocked:
|
|
100
|
+
m.blocked_total.labels(stop_reason=stop_reason).inc()
|
|
101
|
+
|
|
102
|
+
elapsed_ms = float(getattr(e, "elapsed_ms", 0.0) or 0.0)
|
|
103
|
+
if elapsed_ms > 0:
|
|
104
|
+
m.turn_duration_seconds.labels(route=route).observe(elapsed_ms / 1000.0)
|
|
105
|
+
|
|
106
|
+
# ── per-stage breakdown ──────────────────────────────────────────────────────────
|
|
107
|
+
for s in getattr(e, "stages", None) or []:
|
|
108
|
+
stage = getattr(s, "stage", "") or "unknown"
|
|
109
|
+
model = getattr(s, "model", "") or "unknown"
|
|
110
|
+
s_ms = float(getattr(s, "elapsed_ms", 0.0) or 0.0)
|
|
111
|
+
if s_ms > 0:
|
|
112
|
+
m.stage_duration_seconds.labels(stage=stage).observe(s_ms / 1000.0)
|
|
113
|
+
tin = int(getattr(s, "tokens_in", 0) or 0)
|
|
114
|
+
tout = int(getattr(s, "tokens_out", 0) or 0)
|
|
115
|
+
temb = int(getattr(s, "embedding_tokens", 0) or 0)
|
|
116
|
+
if tin:
|
|
117
|
+
m.stage_tokens_total.labels(stage=stage, model=model, direction="in").inc(tin)
|
|
118
|
+
if tout:
|
|
119
|
+
m.stage_tokens_total.labels(stage=stage, model=model, direction="out").inc(tout)
|
|
120
|
+
if temb:
|
|
121
|
+
m.stage_tokens_total.labels(stage=stage, model=model,
|
|
122
|
+
direction="embedding").inc(temb)
|
|
123
|
+
|
|
124
|
+
cost = float(getattr(e, "cost_usd", 0.0) or 0.0)
|
|
125
|
+
if cost > 0:
|
|
126
|
+
m.cost_usd_total.inc(cost)
|
|
127
|
+
|
|
128
|
+
# ── quality / reliability ────────────────────────────────────────────────────────
|
|
129
|
+
drift = float(getattr(e, "drift_cumulative", 0.0) or 0.0)
|
|
130
|
+
if drift > 0:
|
|
131
|
+
m.drift_score.observe(drift)
|
|
132
|
+
action = getattr(e, "drift_action", "") or ""
|
|
133
|
+
if action:
|
|
134
|
+
m.drift_actions_total.labels(action=action).inc()
|
|
135
|
+
|
|
136
|
+
tool_calls = int(getattr(e, "tool_calls", 0) or 0)
|
|
137
|
+
if tool_calls:
|
|
138
|
+
m.tool_calls_total.inc(tool_calls)
|
|
139
|
+
tool_failures = int(getattr(e, "tool_failures", 0) or 0)
|
|
140
|
+
if tool_failures:
|
|
141
|
+
m.tool_failures_total.inc(tool_failures)
|
|
142
|
+
failovers = int(getattr(e, "failover_count", 0) or 0)
|
|
143
|
+
if failovers:
|
|
144
|
+
m.failovers_total.inc(failovers)
|
|
145
|
+
corrections = int(getattr(e, "correction_count", 0) or 0)
|
|
146
|
+
if corrections:
|
|
147
|
+
m.self_corrections_total.inc(corrections)
|
|
148
|
+
if getattr(e, "handoff", False):
|
|
149
|
+
m.handoffs_total.inc()
|
|
150
|
+
# protection nets (see cogno-host grounding.py / provenance.py)
|
|
151
|
+
grounding_rule = getattr(e, "grounding_rule", "") or ""
|
|
152
|
+
if grounding_rule:
|
|
153
|
+
m.grounding_rewrites_total.labels(
|
|
154
|
+
rule=grounding_rule,
|
|
155
|
+
repaired=_b(getattr(e, "grounding_repaired", False))).inc()
|
|
156
|
+
provenance_refusals = int(getattr(e, "provenance_refusals", 0) or 0)
|
|
157
|
+
if provenance_refusals:
|
|
158
|
+
m.provenance_refusals_total.inc(provenance_refusals)
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cogno-observability
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: SRE/Ops monitoring for the Cogno stack — Prometheus metrics sink + /metrics wiring + Grafana dashboards/alerts. Cross-tenant fleet health (NOT the tenant-facing Radar Tokens; NOT billing).
|
|
5
|
+
Author: Vinicius Vale
|
|
6
|
+
Maintainer: Sudoers AI
|
|
7
|
+
License: Apache-2.0
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: prometheus-client>=0.20
|
|
12
|
+
Provides-Extra: http
|
|
13
|
+
Requires-Dist: prometheus-fastapi-instrumentator>=7.0; extra == "http"
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
16
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
|
|
17
|
+
Requires-Dist: pytest-cov>=5.0; extra == "dev"
|
|
18
|
+
Requires-Dist: prometheus-fastapi-instrumentator>=7.0; extra == "dev"
|
|
19
|
+
Requires-Dist: fastapi>=0.110; extra == "dev"
|
|
20
|
+
Requires-Dist: httpx>=0.27; extra == "dev"
|
|
21
|
+
Requires-Dist: ruff>=0.5; extra == "dev"
|
|
22
|
+
Requires-Dist: mypy>=1.8; extra == "dev"
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# cogno-observability
|
|
26
|
+
|
|
27
|
+
**SRE/Ops monitoring for the [Cogno](https://github.com/sudoers-ai/cogno-anima) stack** — a Prometheus metrics sink + `/metrics` wiring + Grafana dashboards/alerts, plus a one-login deploy stack for metrics **and** live logs.
|
|
28
|
+
|
|
29
|
+
Where [`cogno-anima`](https://github.com/sudoers-ai/cogno-anima) is the *mind* and [`cogno-homeo`](https://github.com/sudoers-ai/cogno-homeo) keeps the calls *alive*, `cogno-observability` is the **operator's eyes** on the running fleet — how many turns, how fast, how much they cost, where they fail. It attaches to the host from *outside* its cognition, so the host never imports `prometheus_client`.
|
|
30
|
+
|
|
31
|
+
> Status: **alpha** — metrics sink + `/metrics` wiring + deploy stack + unit/contract suite in place.
|
|
32
|
+
|
|
33
|
+
SRE/Ops monitoring is the *operator-facing* pillar — cross-tenant fleet health — and is
|
|
34
|
+
deliberately **separate** from two other consumers of the same turn data:
|
|
35
|
+
|
|
36
|
+
| Surface | Audience | This repo? |
|
|
37
|
+
|---|---|---|
|
|
38
|
+
| **Fleet monitoring** (Prometheus/Grafana, cross-tenant) | operator / SRE | ✅ **yes** |
|
|
39
|
+
| **Radar Tokens** (per-tenant usage, from the `token_ledger`) | the tenant/customer | ❌ cogno-ui |
|
|
40
|
+
| **Billing / BudgetGuard** (quota, spend) | the platform | ❌ cogno-host + cogno-meter |
|
|
41
|
+
|
|
42
|
+
## Why a separate repo
|
|
43
|
+
|
|
44
|
+
The house rule is **libs emit, host configures** — and the host stays **prometheus-agnostic**. It
|
|
45
|
+
emits one `TurnEvent` per turn to an injected `MetricsSink` and exposes an `instrument(app)` hook;
|
|
46
|
+
it never imports `prometheus_client`. This package fills both seams, so the Prometheus dependency,
|
|
47
|
+
the metric catalog, and the dashboards live here — swappable, versioned independently, and absent
|
|
48
|
+
from a deployment that doesn't want them.
|
|
49
|
+
|
|
50
|
+
## Logs ≠ metrics
|
|
51
|
+
|
|
52
|
+
Two different pipelines. **Logs** (host `configure_logging` → stdout → Loki/ELK) answer *"what
|
|
53
|
+
happened in this turn?"* and may carry high-cardinality `tenant`/`identity`/`session`. **Metrics**
|
|
54
|
+
(this repo) answer *"how is the fleet doing?"* — aggregate series with **low-cardinality labels
|
|
55
|
+
only**. `session_id`/`identity_id` are **never** Prometheus labels (they'd blow up the TSDB); use
|
|
56
|
+
logs for per-turn tracing. `tenant` is opt-in and capped (`PrometheusMetricsSink(tenant_label=True)`).
|
|
57
|
+
|
|
58
|
+
## Install
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pip install cogno-observability # core (prometheus-client)
|
|
62
|
+
pip install "cogno-observability[http]" # + per-route HTTP RED metrics (fastapi instrumentator)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Wire it into the host
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from cogno_host.api.pg_app import create_pg_app
|
|
69
|
+
from cogno_observability import PrometheusMetricsSink, attach
|
|
70
|
+
|
|
71
|
+
app = create_pg_app(
|
|
72
|
+
dsn, auth=admin,
|
|
73
|
+
metrics_sink=PrometheusMetricsSink(), # per-turn TurnEvent → Prometheus series
|
|
74
|
+
instrument=attach, # mounts /metrics + HTTP instrumentation
|
|
75
|
+
)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
With neither argument the host runs exactly as before (no-op sink, no `/metrics`).
|
|
79
|
+
|
|
80
|
+
## Metrics
|
|
81
|
+
|
|
82
|
+
| Metric | Type | Labels | Meaning |
|
|
83
|
+
|---|---|---|---|
|
|
84
|
+
| `cogno_turns_total` | counter | route, stop_reason, ok, blocked, cache_hit | turn outcomes |
|
|
85
|
+
| `cogno_turn_errors_total` | counter | error | unhandled exceptions (by class) |
|
|
86
|
+
| `cogno_turn_duration_seconds` | histogram | route | end-to-end latency |
|
|
87
|
+
| `cogno_stage_duration_seconds` | histogram | stage | per cognitive-stage latency |
|
|
88
|
+
| `cogno_stage_tokens_total` | counter | stage, model, direction | tokens (in/out/embedding) |
|
|
89
|
+
| `cogno_cost_usd_total` | counter | — | provider spend (0 for local) |
|
|
90
|
+
| `cogno_drift_score` | histogram | — | cumulative drift distribution |
|
|
91
|
+
| `cogno_drift_actions_total` | counter | action | drift-triggered actions |
|
|
92
|
+
| `cogno_tool_calls_total` / `_failures_total` | counter | — | EGO tool calls / failures |
|
|
93
|
+
| `cogno_failovers_total`, `cogno_self_corrections_total`, `cogno_handoffs_total` | counter | — | reliability |
|
|
94
|
+
| `cogno_blocked_total` | counter | stop_reason | safety/quota/PII blocks |
|
|
95
|
+
|
|
96
|
+
Plus HTTP RED metrics (`http_request_*`) from the instrumentator.
|
|
97
|
+
|
|
98
|
+
## Multi-worker
|
|
99
|
+
|
|
100
|
+
Each uvicorn/gunicorn worker has its own registry. Set `PROMETHEUS_MULTIPROC_DIR` to a shared
|
|
101
|
+
(empty at boot) dir and `attach` will reconcile across workers via `MultiProcessCollector` at scrape
|
|
102
|
+
time. Without it, single-process mode is used.
|
|
103
|
+
|
|
104
|
+
## Ops assets (`ops/`)
|
|
105
|
+
|
|
106
|
+
- `alerts/cogno_rules.yml` — Prometheus recording + alerting rules.
|
|
107
|
+
- `dashboards/cogno_overview.json` — Grafana dashboard (import, pick your Prometheus datasource).
|
|
108
|
+
- `dashboards/cogno_logs.json` — Grafana dashboard for live logs (Loki).
|
|
109
|
+
- `prometheus-scrape.example.yml` — scrape config / ServiceMonitor example.
|
|
110
|
+
- `SLOs.md` — starting SLOs + a metric→runbook map.
|
|
111
|
+
|
|
112
|
+
## Deploy — one Grafana login for metrics + logs
|
|
113
|
+
|
|
114
|
+
`deploy/` is a docker-compose stack (Prometheus + Loki + Promtail + Grafana) that watches an
|
|
115
|
+
existing host and gives you **one Grafana login** to follow it live — metrics and near-real-time
|
|
116
|
+
logs on the same pane. See [`deploy/README.md`](deploy/README.md).
|
|
117
|
+
|
|
118
|
+
## Host integration
|
|
119
|
+
|
|
120
|
+
The host exposes two seams (`metrics_sink=` + `instrument(app)`) and stays prometheus-agnostic;
|
|
121
|
+
this library fills them. See [`docs/HOST_INTEGRATION.md`](docs/HOST_INTEGRATION.md).
|
|
122
|
+
|
|
123
|
+
## The Cogno ecosystem
|
|
124
|
+
|
|
125
|
+
`cogno-observability` is one organ of **[Cogno](https://github.com/sudoers-ai)** — a family of
|
|
126
|
+
small, composable, Apache-2.0 libraries that together form a complete conversational-agent
|
|
127
|
+
platform. Each library owns a single concern and stays infra-agnostic; a **host** assembles them
|
|
128
|
+
into a running agent:
|
|
129
|
+
|
|
130
|
+

|
|
131
|
+
|
|
132
|
+
The open-source libraries are the organs; the **host is the body** that joins them. Our reference
|
|
133
|
+
host — `cogno-host`, with its `cogno-ui` dashboard — is the private product layer, but it holds no
|
|
134
|
+
special powers: everything it does rides on the public seams documented in each library's
|
|
135
|
+
`docs/HOST_INTEGRATION.md`.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
cogno_observability/__init__.py
|
|
5
|
+
cogno_observability/instrument.py
|
|
6
|
+
cogno_observability/metrics.py
|
|
7
|
+
cogno_observability/sink.py
|
|
8
|
+
cogno_observability.egg-info/PKG-INFO
|
|
9
|
+
cogno_observability.egg-info/SOURCES.txt
|
|
10
|
+
cogno_observability.egg-info/dependency_links.txt
|
|
11
|
+
cogno_observability.egg-info/requires.txt
|
|
12
|
+
cogno_observability.egg-info/top_level.txt
|
|
13
|
+
tests/test_contract.py
|
|
14
|
+
tests/test_instrument.py
|
|
15
|
+
tests/test_sink.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cogno_observability
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cogno-observability"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "SRE/Ops monitoring for the Cogno stack — Prometheus metrics sink + /metrics wiring + Grafana dashboards/alerts. Cross-tenant fleet health (NOT the tenant-facing Radar Tokens; NOT billing)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "Apache-2.0" }
|
|
12
|
+
authors = [{ name = "Vinicius Vale" }]
|
|
13
|
+
maintainers = [{ name = "Sudoers AI" }]
|
|
14
|
+
dependencies = [
|
|
15
|
+
"prometheus-client>=0.20",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
# The FastAPI HTTP-layer instrumentation (RED metrics per route) is optional: the business
|
|
20
|
+
# metrics (per-turn TurnEvent) work without it.
|
|
21
|
+
http = ["prometheus-fastapi-instrumentator>=7.0"]
|
|
22
|
+
dev = [
|
|
23
|
+
"pytest>=8",
|
|
24
|
+
"pytest-asyncio>=0.23",
|
|
25
|
+
"pytest-cov>=5.0",
|
|
26
|
+
"prometheus-fastapi-instrumentator>=7.0",
|
|
27
|
+
"fastapi>=0.110",
|
|
28
|
+
"httpx>=0.27",
|
|
29
|
+
"ruff>=0.5",
|
|
30
|
+
"mypy>=1.8",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[tool.setuptools.packages.find]
|
|
34
|
+
include = ["cogno_observability*"]
|
|
35
|
+
|
|
36
|
+
[tool.pytest.ini_options]
|
|
37
|
+
asyncio_mode = "auto"
|
|
38
|
+
testpaths = ["tests"]
|
|
39
|
+
|
|
40
|
+
[tool.ruff]
|
|
41
|
+
line-length = 110
|
|
42
|
+
target-version = "py310"
|
|
43
|
+
|
|
44
|
+
[tool.ruff.lint]
|
|
45
|
+
select = ["E4", "E7", "E9", "F"]
|
|
46
|
+
|
|
47
|
+
[tool.mypy]
|
|
48
|
+
python_version = "3.10"
|
|
49
|
+
ignore_missing_imports = true
|
|
50
|
+
files = ["cogno_observability"]
|
|
51
|
+
warn_unused_ignores = true
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Cross-repo contract: the host's real ``TurnEvent`` drives ``PrometheusMetricsSink``.
|
|
2
|
+
|
|
3
|
+
The sink duck-types the event, so a silent field rename on the host would degrade a metric to 0
|
|
4
|
+
with no failing test. This test closes that gap by importing the **real** ``cogno_host.TurnEvent``
|
|
5
|
+
and asserting (a) it satisfies the ``TurnEventLike`` shape the sink relies on, and (b) a real event
|
|
6
|
+
actually populates the series end-to-end. Auto-skips if cogno-host isn't installed (this repo stays
|
|
7
|
+
standalone)."""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import pytest
|
|
12
|
+
from prometheus_client import CollectorRegistry
|
|
13
|
+
|
|
14
|
+
from cogno_observability import PrometheusMetricsSink
|
|
15
|
+
from cogno_observability.sink import TurnEventLike
|
|
16
|
+
|
|
17
|
+
cogno_host = pytest.importorskip("cogno_host", reason="cogno-host not installed")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_real_turnevent_satisfies_sink_shape():
|
|
21
|
+
# runtime_checkable Protocol → isinstance verifies every attribute the sink reads exists.
|
|
22
|
+
e = cogno_host.TurnEvent(tenant_id="acme", session_id="s1")
|
|
23
|
+
assert isinstance(e, TurnEventLike)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_real_turnevent_drives_the_series_end_to_end():
|
|
27
|
+
reg = CollectorRegistry()
|
|
28
|
+
sink = PrometheusMetricsSink(registry=reg)
|
|
29
|
+
e = cogno_host.TurnEvent(
|
|
30
|
+
tenant_id="acme", session_id="s1", route="EGO", stop_reason="completed",
|
|
31
|
+
total_tokens=15, elapsed_ms=1200.0, cost_usd=0.002, drift_cumulative=0.3,
|
|
32
|
+
drift_action="warn", tool_calls=1, handoff=False,
|
|
33
|
+
stages=[cogno_host.StageSample(stage="ner", model="mistral",
|
|
34
|
+
tokens_in=10, tokens_out=5, elapsed_ms=200.0)])
|
|
35
|
+
sink.record(e)
|
|
36
|
+
|
|
37
|
+
assert reg.get_sample_value("cogno_turns_total", {
|
|
38
|
+
"route": "EGO", "stop_reason": "completed", "ok": "true",
|
|
39
|
+
"blocked": "false", "cache_hit": "false"}) == 1.0
|
|
40
|
+
assert reg.get_sample_value("cogno_stage_tokens_total",
|
|
41
|
+
{"stage": "ner", "model": "mistral", "direction": "in"}) == 10.0
|
|
42
|
+
assert reg.get_sample_value("cogno_drift_actions_total", {"action": "warn"}) == 1.0
|
|
43
|
+
assert reg.get_sample_value("cogno_turn_duration_seconds_count", {"route": "EGO"}) == 1.0
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_sink_reads_every_field_the_host_provides():
|
|
47
|
+
# Belt-and-suspenders: every attribute named in TurnEventLike is present on the host DTO, so
|
|
48
|
+
# the getattr defaults in the sink are a safety net, never the actual data path.
|
|
49
|
+
e = cogno_host.TurnEvent(tenant_id="acme", session_id="s1")
|
|
50
|
+
for field in TurnEventLike.__annotations__:
|
|
51
|
+
assert hasattr(e, field), f"host TurnEvent is missing '{field}' the sink reads"
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""attach(app) mounts a working /metrics endpoint and instruments HTTP routes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from fastapi import FastAPI
|
|
6
|
+
from fastapi.testclient import TestClient
|
|
7
|
+
|
|
8
|
+
from cogno_observability import PrometheusMetricsSink, attach
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _app() -> FastAPI:
|
|
12
|
+
app = FastAPI()
|
|
13
|
+
attach(app) # mounts /metrics + HTTP instrumentation (before routes)
|
|
14
|
+
|
|
15
|
+
@app.get("/ping")
|
|
16
|
+
def ping() -> dict:
|
|
17
|
+
return {"ok": True}
|
|
18
|
+
|
|
19
|
+
return app
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_metrics_endpoint_exposes_series():
|
|
23
|
+
app = _app()
|
|
24
|
+
# record a business metric onto the global registry the endpoint scrapes
|
|
25
|
+
from types import SimpleNamespace
|
|
26
|
+
PrometheusMetricsSink().record(SimpleNamespace(
|
|
27
|
+
route="EGO", stop_reason="completed", ok=True, blocked=False, cache_hit=False,
|
|
28
|
+
elapsed_ms=500, stages=[], cost_usd=0.0, drift_cumulative=0.0, drift_action="",
|
|
29
|
+
tool_calls=0, tool_failures=0, failover_count=0, correction_count=0, handoff=False,
|
|
30
|
+
error="", tenant_id="acme", total_tokens=0))
|
|
31
|
+
client = TestClient(app)
|
|
32
|
+
client.get("/ping") # generate an HTTP-layer sample
|
|
33
|
+
body = client.get("/metrics").text
|
|
34
|
+
assert "cogno_turns_total" in body # business metric
|
|
35
|
+
assert "http_request" in body or "http_requests" in body # HTTP RED (instrumentator)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_metrics_endpoint_ok_without_http_extra():
|
|
39
|
+
# instrument_http=False must still serve /metrics (business metrics only)
|
|
40
|
+
app = FastAPI()
|
|
41
|
+
attach(app, instrument_http=False)
|
|
42
|
+
body = TestClient(app).get("/metrics").text
|
|
43
|
+
assert "python_info" in body or "cogno_" in body # a valid exposition page
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Unit tests for PrometheusMetricsSink — TurnEvent → Prometheus series (fresh registry each)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
from prometheus_client import CollectorRegistry
|
|
9
|
+
|
|
10
|
+
from cogno_observability import PrometheusMetricsSink
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# ── minimal stand-ins for the host's TurnEvent / StageSample (duck-typed, no cogno_host dep) ──
|
|
14
|
+
@dataclass
|
|
15
|
+
class Stage:
|
|
16
|
+
stage: str
|
|
17
|
+
model: str = "fake"
|
|
18
|
+
tokens_in: int = 0
|
|
19
|
+
tokens_out: int = 0
|
|
20
|
+
embedding_tokens: int = 0
|
|
21
|
+
elapsed_ms: float = 0.0
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Event:
|
|
26
|
+
tenant_id: str = "acme"
|
|
27
|
+
route: str = "EGO"
|
|
28
|
+
stop_reason: str = "completed"
|
|
29
|
+
total_tokens: int = 0
|
|
30
|
+
elapsed_ms: float = 0.0
|
|
31
|
+
cache_hit: bool = False
|
|
32
|
+
blocked: bool = False
|
|
33
|
+
ok: bool = True
|
|
34
|
+
error: str = ""
|
|
35
|
+
cost_usd: float = 0.0
|
|
36
|
+
drift_cumulative: float = 0.0
|
|
37
|
+
drift_action: str = ""
|
|
38
|
+
tool_calls: int = 0
|
|
39
|
+
tool_failures: int = 0
|
|
40
|
+
failover_count: int = 0
|
|
41
|
+
correction_count: int = 0
|
|
42
|
+
handoff: bool = False
|
|
43
|
+
grounding_rule: str = ""
|
|
44
|
+
grounding_repaired: bool = False
|
|
45
|
+
provenance_refusals: int = 0
|
|
46
|
+
stages: list = field(default_factory=list)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@pytest.fixture
|
|
50
|
+
def reg():
|
|
51
|
+
return CollectorRegistry()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_turn_counter_and_latency(reg):
|
|
55
|
+
sink = PrometheusMetricsSink(registry=reg)
|
|
56
|
+
sink.record(Event(route="EGO", stop_reason="completed", elapsed_ms=1500))
|
|
57
|
+
v = reg.get_sample_value("cogno_turns_total", {
|
|
58
|
+
"route": "EGO", "stop_reason": "completed", "ok": "true",
|
|
59
|
+
"blocked": "false", "cache_hit": "false"})
|
|
60
|
+
assert v == 1.0
|
|
61
|
+
assert reg.get_sample_value("cogno_turn_duration_seconds_count", {"route": "EGO"}) == 1.0
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_failed_turn_increments_errors(reg):
|
|
65
|
+
sink = PrometheusMetricsSink(registry=reg)
|
|
66
|
+
sink.record(Event(ok=False, error="MCPDispatchError", stop_reason="error"))
|
|
67
|
+
assert reg.get_sample_value("cogno_turn_errors_total", {"error": "MCPDispatchError"}) == 1.0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_stage_tokens_by_model_and_direction(reg):
|
|
71
|
+
sink = PrometheusMetricsSink(registry=reg)
|
|
72
|
+
sink.record(Event(stages=[
|
|
73
|
+
Stage("ner", model="mistral", tokens_in=100, tokens_out=40, elapsed_ms=200),
|
|
74
|
+
Stage("id", model="heuristic", embedding_tokens=12),
|
|
75
|
+
]))
|
|
76
|
+
assert reg.get_sample_value("cogno_stage_tokens_total",
|
|
77
|
+
{"stage": "ner", "model": "mistral", "direction": "in"}) == 100.0
|
|
78
|
+
assert reg.get_sample_value("cogno_stage_tokens_total",
|
|
79
|
+
{"stage": "ner", "model": "mistral", "direction": "out"}) == 40.0
|
|
80
|
+
assert reg.get_sample_value("cogno_stage_tokens_total",
|
|
81
|
+
{"stage": "id", "model": "heuristic",
|
|
82
|
+
"direction": "embedding"}) == 12.0
|
|
83
|
+
assert reg.get_sample_value("cogno_stage_duration_seconds_count", {"stage": "ner"}) == 1.0
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_cost_drift_tools_reliability(reg):
|
|
87
|
+
sink = PrometheusMetricsSink(registry=reg)
|
|
88
|
+
sink.record(Event(cost_usd=0.0123, drift_cumulative=0.42, drift_action="warn",
|
|
89
|
+
tool_calls=3, tool_failures=1, failover_count=2,
|
|
90
|
+
correction_count=1, handoff=True))
|
|
91
|
+
assert reg.get_sample_value("cogno_cost_usd_total") == pytest.approx(0.0123)
|
|
92
|
+
assert reg.get_sample_value("cogno_drift_actions_total", {"action": "warn"}) == 1.0
|
|
93
|
+
assert reg.get_sample_value("cogno_drift_score_count") == 1.0
|
|
94
|
+
assert reg.get_sample_value("cogno_tool_calls_total") == 3.0
|
|
95
|
+
assert reg.get_sample_value("cogno_tool_failures_total") == 1.0
|
|
96
|
+
assert reg.get_sample_value("cogno_failovers_total") == 2.0
|
|
97
|
+
assert reg.get_sample_value("cogno_self_corrections_total") == 1.0
|
|
98
|
+
assert reg.get_sample_value("cogno_handoffs_total") == 1.0
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def test_blocked_turn_counted(reg):
|
|
102
|
+
sink = PrometheusMetricsSink(registry=reg)
|
|
103
|
+
sink.record(Event(blocked=True, stop_reason="quota_exceeded"))
|
|
104
|
+
assert reg.get_sample_value("cogno_blocked_total", {"stop_reason": "quota_exceeded"}) == 1.0
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def test_record_never_raises_on_garbage(reg):
|
|
108
|
+
sink = PrometheusMetricsSink(registry=reg)
|
|
109
|
+
sink.record(object()) # missing every attribute → swallowed, no exception
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def test_tenant_label_opt_in(reg):
|
|
113
|
+
sink = PrometheusMetricsSink(registry=reg, tenant_label=True)
|
|
114
|
+
sink.record(Event(tenant_id="acme"))
|
|
115
|
+
assert reg.get_sample_value("cogno_turns_by_tenant_total",
|
|
116
|
+
{"tenant": "acme", "ok": "true"}) == 1.0
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_two_sinks_on_same_registry_share_series(reg):
|
|
120
|
+
# A second sink on the same registry must not crash (Duplicated timeseries) — it reuses the
|
|
121
|
+
# existing collectors, so counts from both accumulate onto one series.
|
|
122
|
+
s1 = PrometheusMetricsSink(registry=reg)
|
|
123
|
+
s2 = PrometheusMetricsSink(registry=reg) # must NOT raise
|
|
124
|
+
s1.record(Event(route="EGO", stop_reason="completed"))
|
|
125
|
+
s2.record(Event(route="EGO", stop_reason="completed"))
|
|
126
|
+
assert reg.get_sample_value("cogno_turns_total", {
|
|
127
|
+
"route": "EGO", "stop_reason": "completed", "ok": "true",
|
|
128
|
+
"blocked": "false", "cache_hit": "false"}) == 2.0
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def test_two_default_registry_sinks_do_not_crash():
|
|
132
|
+
# The real-world footgun: PrometheusMetricsSink() twice on the global REGISTRY.
|
|
133
|
+
PrometheusMetricsSink()
|
|
134
|
+
PrometheusMetricsSink() # must NOT raise
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def test_protection_net_counters(reg):
|
|
138
|
+
# grounding rewrite (rule + repaired) and provenance refusals land as counters; a clean
|
|
139
|
+
# turn (empty rule, zero refusals) emits neither series.
|
|
140
|
+
sink = PrometheusMetricsSink(registry=reg)
|
|
141
|
+
sink.record(Event(grounding_rule="performative_without_commit", grounding_repaired=True,
|
|
142
|
+
provenance_refusals=2))
|
|
143
|
+
sink.record(Event()) # clean turn → no net samples
|
|
144
|
+
assert reg.get_sample_value("cogno_grounding_rewrites_total", {
|
|
145
|
+
"rule": "performative_without_commit", "repaired": "true"}) == 1.0
|
|
146
|
+
assert reg.get_sample_value("cogno_provenance_refusals_total") == 2.0
|