pooledbounds 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.
- pooledbounds-0.2.0/LICENSE +21 -0
- pooledbounds-0.2.0/PKG-INFO +257 -0
- pooledbounds-0.2.0/README.md +247 -0
- pooledbounds-0.2.0/pyproject.toml +17 -0
- pooledbounds-0.2.0/setup.cfg +4 -0
- pooledbounds-0.2.0/src/pooledbounds/__init__.py +5 -0
- pooledbounds-0.2.0/src/pooledbounds/__main__.py +3 -0
- pooledbounds-0.2.0/src/pooledbounds/cli.py +106 -0
- pooledbounds-0.2.0/src/pooledbounds/core.py +182 -0
- pooledbounds-0.2.0/src/pooledbounds/objectives.py +51 -0
- pooledbounds-0.2.0/src/pooledbounds.egg-info/PKG-INFO +257 -0
- pooledbounds-0.2.0/src/pooledbounds.egg-info/SOURCES.txt +18 -0
- pooledbounds-0.2.0/src/pooledbounds.egg-info/dependency_links.txt +1 -0
- pooledbounds-0.2.0/src/pooledbounds.egg-info/entry_points.txt +2 -0
- pooledbounds-0.2.0/src/pooledbounds.egg-info/top_level.txt +1 -0
- pooledbounds-0.2.0/tests/test_cli.py +190 -0
- pooledbounds-0.2.0/tests/test_core.py +263 -0
- pooledbounds-0.2.0/tests/test_objectives.py +154 -0
- pooledbounds-0.2.0/tests/test_plain_arguments.py +53 -0
- pooledbounds-0.2.0/tests/test_rank_index.py +109 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Anish Pentyala
|
|
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. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pooledbounds
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Bounds, not interpolated guesses, for pooled unequal-bin histograms
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# pooledbounds
|
|
12
|
+
|
|
13
|
+
What can pooled p95 actually be when two teams sent histograms with different
|
|
14
|
+
bucket edges? `pooledbounds` keeps the uncertainty instead of making up a
|
|
15
|
+
within-bucket distribution.
|
|
16
|
+
|
|
17
|
+
It computes tight nearest-rank quantile bounds and exact lower/upper counts at
|
|
18
|
+
chosen thresholds. Histograms may have different edges. No shared-edge
|
|
19
|
+
rebucketing, linear interpolation, or expansion into individual observations is
|
|
20
|
+
needed. It also supplies compressed raw-population witnesses attaining both
|
|
21
|
+
threshold count bounds.
|
|
22
|
+
|
|
23
|
+
This is an offline arithmetic tool, not a Prometheus query engine, confidence
|
|
24
|
+
interval estimator, or proof that telemetry is correct.
|
|
25
|
+
|
|
26
|
+
## Example
|
|
27
|
+
|
|
28
|
+
Install from a checked-out copy with `pip install .`, then:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
pooledbounds examples/mixed-bins.json --quantile 0.95 --threshold 120
|
|
32
|
+
# or
|
|
33
|
+
python -m pooledbounds examples/mixed-bins.json --quantile 0.95
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The example combines 100 observations in each of two disjoint regions:
|
|
37
|
+
|
|
38
|
+
| Region | Histogram intervals with nonzero counts |
|
|
39
|
+
| --- | --- |
|
|
40
|
+
| A | 90 in (0,100], 10 in (100,200] |
|
|
41
|
+
| B | 50 in (0,150], 50 in (150,300] |
|
|
42
|
+
|
|
43
|
+
The pooled p95 is **strictly greater than 150 and at most 300**. Between 90 and
|
|
44
|
+
150 of the 200 observations are at or below 120, so the exact attainable fraction
|
|
45
|
+
range is [9/20, 3/4]. A point estimate inside those ranges needs an extra
|
|
46
|
+
assumption. Keeping only common finite edges would retain just 0 here and lose
|
|
47
|
+
useful information.
|
|
48
|
+
|
|
49
|
+
## Input contract
|
|
50
|
+
|
|
51
|
+
```json
|
|
52
|
+
{
|
|
53
|
+
"schema": 1,
|
|
54
|
+
"populations": "disjoint-finite-observations",
|
|
55
|
+
"histograms": [
|
|
56
|
+
{"id": "a", "edges": ["0", "100", "200"], "counts": [0, 90, 10, 0]},
|
|
57
|
+
{"id": "b", "edges": ["0", "150", "300"], "counts": [0, 50, 50, 0]}
|
|
58
|
+
]
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
- Counts are nonnegative **integers per bucket**, not cumulative counts,
|
|
63
|
+
weights, rates, or values already divided by a sampling factor.
|
|
64
|
+
- Edges are finite decimal strings in strictly increasing order. Scientific
|
|
65
|
+
notation is allowed. Strings avoid silently rounding decimals through binary
|
|
66
|
+
floating point. JSON numbers are not accepted for edges or query values.
|
|
67
|
+
- With edges `[a,b]`, counts describe `(-infinity,a]`, `(a,b]`, and
|
|
68
|
+
`(b,+infinity)`. All observations are finite real numbers. Empty edges with
|
|
69
|
+
one count mean the whole real line. Zero-count buckets are allowed.
|
|
70
|
+
- Histograms must describe disjoint observations. Repeated cumulative snapshots
|
|
71
|
+
of the same counter are **not** separate populations. The declaration is an
|
|
72
|
+
assumption supplied by the caller; the tool cannot verify disjointness or
|
|
73
|
+
distinguish a plausible cumulative count vector from per-bucket counts.
|
|
74
|
+
- Histogram IDs must be unique. Unknown fields, duplicate JSON keys, malformed
|
|
75
|
+
counts, non-increasing edges, and empty pooled populations are invalid.
|
|
76
|
+
- Units must already match. There is no implicit milliseconds/seconds conversion.
|
|
77
|
+
|
|
78
|
+
The input is not an OpenTelemetry or Prometheus export. Convert and check the
|
|
79
|
+
measurement interval, reset behavior, temporality, units and bucket convention
|
|
80
|
+
first. Do not feed `rate()` results as integer counts. `+Inf` observations,
|
|
81
|
+
`-Inf` observations and NaNs are outside this model, even though bins can have
|
|
82
|
+
unbounded endpoints.
|
|
83
|
+
|
|
84
|
+
## Quantile meaning and output
|
|
85
|
+
|
|
86
|
+
`--quantile` is repeatable; its default is 0.5, 0.95, 0.99. For `0 < q <= 1`,
|
|
87
|
+
nearest rank is `ceil(q*N)` in the pooled sorted raw population. The lower
|
|
88
|
+
endpoint is an infimum, **not an attained minimum**. A finite upper endpoint is
|
|
89
|
+
attainable. Unbounded tails are explicit `-infinity`/`+infinity`, never replaced
|
|
90
|
+
with a convenient finite estimate. There is no q=0 convention and no linear
|
|
91
|
+
sample-quantile interpolation.
|
|
92
|
+
|
|
93
|
+
All finite output values use exact rational objects:
|
|
94
|
+
|
|
95
|
+
```json
|
|
96
|
+
{"numerator": "3", "denominator": "4"}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Each quantile includes its rank and the sorted endpoint bucket crossing that
|
|
100
|
+
rank, with counts before and through that bucket. These are arithmetic
|
|
101
|
+
certificates under the input assumptions, not a cryptographic proof or raw-data
|
|
102
|
+
audit. Equal endpoint ties can choose a different provenance bucket if the
|
|
103
|
+
histograms are reordered; numerical bounds are unchanged.
|
|
104
|
+
|
|
105
|
+
`--threshold` is repeatable and asks for the number of observations **<=** that
|
|
106
|
+
value. Both count extrema are attained. Each witness lists one rational value
|
|
107
|
+
and multiplicity for every occupied input bucket. It preserves every supplied
|
|
108
|
+
bucket count, so the report does not expand a count of a billion into a billion
|
|
109
|
+
rows. It does not claim that either synthetic population was actually observed.
|
|
110
|
+
|
|
111
|
+
`input_sha256` binds the parsed document's canonical JSON representation
|
|
112
|
+
(sorted keys, compact separators, ASCII escapes), not its raw file bytes. It is
|
|
113
|
+
not a signature. It does not validate the input assumptions.
|
|
114
|
+
|
|
115
|
+
## Why the bounds are tight
|
|
116
|
+
|
|
117
|
+
Think of each count as repeated unknown values constrained to a bucket
|
|
118
|
+
`(lower,upper]`. For any feasible raw population, sorting the lower endpoints
|
|
119
|
+
bounds its kth value strictly from below; sorting the upper endpoints bounds
|
|
120
|
+
it from above. The kth lower and kth upper endpoints are therefore a valid
|
|
121
|
+
quantile envelope. Moving each unknown value arbitrarily close to its lower
|
|
122
|
+
endpoint approaches the lower bound. Setting values at finite upper endpoints
|
|
123
|
+
attains the finite upper bound. Unbounded endpoints can be approached without
|
|
124
|
+
finite limits. No probabilistic assumption is involved.
|
|
125
|
+
|
|
126
|
+
At threshold t, a bucket is forced below/equal t only if its upper endpoint is
|
|
127
|
+
<=t. A bucket can contribute below/equal t exactly when its lower endpoint is
|
|
128
|
+
<t. Sum these counts independently across the declared disjoint buckets. The
|
|
129
|
+
emitted witnesses construct both extremes with valid finite representatives.
|
|
130
|
+
The strict comparison matters: values in `(t,u]` cannot be <=t.
|
|
131
|
+
|
|
132
|
+
## Python API
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
from pooledbounds import analyze, InvalidHistogram, Limits
|
|
136
|
+
|
|
137
|
+
report = analyze(document, quantiles=["0.95"], thresholds=["120"])
|
|
138
|
+
# Invalid or out-of-budget inputs raise InvalidHistogram.
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
The API does not mutate the document, access the environment, import a model,
|
|
142
|
+
open a network connection, or install anything. The CLI reads one UTF-8 JSON
|
|
143
|
+
file or `-` for standard input. Exit 0 means a report was computed in the
|
|
144
|
+
declared model, **not that an SLO passed**. Invalid data or I/O returns INVALID
|
|
145
|
+
JSON and exit 2. Argument syntax errors use argparse stderr and exit 2.
|
|
146
|
+
|
|
147
|
+
## Threshold objectives without interpolation
|
|
148
|
+
|
|
149
|
+
When the question is "at least 95% of observations were <=120", use an explicit
|
|
150
|
+
objective instead of treating a successful arithmetic report as a passing SLO:
|
|
151
|
+
|
|
152
|
+
```sh
|
|
153
|
+
pooledbounds examples/mixed-bins.json --objective 120=.95
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
For this example only 90 to 150 of 200 observations can be <=120. The command
|
|
157
|
+
returns `objective_status: "VIOLATED"` and exit 1: even the largest admissible
|
|
158
|
+
fraction, 3/4, is below .95. The same fixture with `120=.7` is
|
|
159
|
+
`INDETERMINATE` (exit 3), and with `120=.45` is `SATISFIED` (exit 0).
|
|
160
|
+
|
|
161
|
+
Each repeatable `--objective THRESHOLD=MINIMUM_FRACTION` requests a minimum
|
|
162
|
+
fraction of observations **<=** its threshold. Fractions are decimal strings
|
|
163
|
+
between 0 and 1 inclusive, not percentages. Comparisons use exact rational
|
|
164
|
+
arithmetic, with no rounding, tolerance or within-bucket interpolation.
|
|
165
|
+
Objectives cannot be combined with `--quantile` or `--threshold`; ordinary
|
|
166
|
+
queries and their exit behavior are unchanged when no objective is supplied.
|
|
167
|
+
|
|
168
|
+
- `SATISFIED`: the minimum possible good fraction is >= the target. Every
|
|
169
|
+
compatible population meets the objective.
|
|
170
|
+
- `VIOLATED`: the maximum possible good fraction is < the target. No compatible
|
|
171
|
+
population meets the objective.
|
|
172
|
+
- `INDETERMINATE`: some compatible populations meet it and some do not. A
|
|
173
|
+
fraction whose upper bound equals the target is not a proven violation.
|
|
174
|
+
|
|
175
|
+
For several objectives, all must hold: any proven violation returns 1;
|
|
176
|
+
otherwise any indeterminate objective returns 3; otherwise the command returns
|
|
177
|
+
0. These minimum-fraction objectives are jointly compatible whenever each is
|
|
178
|
+
individually possible: putting values sufficiently close to each bucket's lower
|
|
179
|
+
endpoint attains all queried maximum counts simultaneously. Invalid input,
|
|
180
|
+
conflicting options and output failure return 2, taking priority over a computed
|
|
181
|
+
verdict. A zero observation total is invalid, not a vacuous pass.
|
|
182
|
+
|
|
183
|
+
The JSON retains the ordinary model status, input digest, total count and
|
|
184
|
+
threshold evidence, including count/fraction extrema and compressed witnesses.
|
|
185
|
+
`objectives` adds each exact target and a zero-based `threshold_index` into
|
|
186
|
+
`thresholds`, plus its verdict. `objective_status` combines the verdicts. Witnesses
|
|
187
|
+
are synthetic compatible populations, not measured requests.
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
from pooledbounds import evaluate_objectives
|
|
191
|
+
|
|
192
|
+
report = evaluate_objectives(document, [
|
|
193
|
+
{"threshold": "120", "minimum_fraction": ".95"},
|
|
194
|
+
])
|
|
195
|
+
assert report["objective_status"] in {"SATISFIED", "VIOLATED", "INDETERMINATE"}
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
This is a decision **inside the declared input model**, not a production SLO
|
|
199
|
+
certification, statistical confidence statement, telemetry-completeness check,
|
|
200
|
+
or live alert. Units, windows, disjointness and correct per-bucket integer counts
|
|
201
|
+
remain the caller's responsibility. Prometheus cumulative snapshots, rates and
|
|
202
|
+
reset handling are still outside the accepted input format. Existing monitoring
|
|
203
|
+
tools are preferable for live SLOs; this mode answers what an already exported,
|
|
204
|
+
unequal-bin population can prove without inventing hidden observations.
|
|
205
|
+
|
|
206
|
+
## Admission limits
|
|
207
|
+
|
|
208
|
+
Defaults: 1,000 histograms, 100,000 total buckets including empty ones,
|
|
209
|
+
1,000 queries, 128 characters per decimal, exponent magnitude <=1,000,
|
|
210
|
+
and total count <=10^18. The CLI reads at most 8 MiB plus one byte before
|
|
211
|
+
refusing a larger input. API callers already hold their documents in memory.
|
|
212
|
+
|
|
213
|
+
`Limits` can adjust histogram, bucket, number-character, total-count and
|
|
214
|
+
query/bucket-work caps. The work cap defaults to 1,000,000 units:
|
|
215
|
+
`occupied_buckets * (quantile_queries + 2 * threshold_queries)`.
|
|
216
|
+
This also bounds the number of threshold witness rows emitted. Endpoints are
|
|
217
|
+
sorted once per side; cumulative integer counts then let each quantile rank
|
|
218
|
+
use binary search instead of rescanning every occupied bucket. Equal endpoint
|
|
219
|
+
ties retain input order and the same bucket certificates. The two cumulative
|
|
220
|
+
count lists add one integer per occupied bucket per side. Threshold witnesses
|
|
221
|
+
still scan buckets, and the original admission-work formula is unchanged.
|
|
222
|
+
Count size does not cause per-observation allocation.
|
|
223
|
+
These are admission limits, not hard RAM, encoded-output-size or CPU guarantees.
|
|
224
|
+
Large rational values and caller-chosen larger caps can still be expensive.
|
|
225
|
+
|
|
226
|
+
## Evidence and scope
|
|
227
|
+
|
|
228
|
+
See [EVIDENCE.md](EVIDENCE.md) for the practical problem and comparison with
|
|
229
|
+
existing histogram tools. This applies elementary order-statistic bounds to a
|
|
230
|
+
specific offline workflow; it does not claim a new statistical method or that
|
|
231
|
+
no other implementation exists. Existing native histogram/sketch tools are
|
|
232
|
+
usually the better choice when you control future instrumentation.
|
|
233
|
+
|
|
234
|
+
Tests include enumeration of every raw population in small integer/half-integer
|
|
235
|
+
fixtures, independent checks of witness bucket membership and counts, exact
|
|
236
|
+
large ranks, unbounded tails, invalid inputs and resource admission. Synthetic
|
|
237
|
+
tests are not evidence of adoption or production accuracy.
|
|
238
|
+
|
|
239
|
+
## Output failures
|
|
240
|
+
|
|
241
|
+
The module and installed command return exit 2 when stdout cannot be written or
|
|
242
|
+
flushed, including a closed pipe or a full device. Already-written partial bytes
|
|
243
|
+
cannot be retracted, so check the exit status before using a report. The process
|
|
244
|
+
runner redirects a failed stdout to the null device before shutdown, preventing
|
|
245
|
+
Python's second flush from replacing exit 2 with exit 120.
|
|
246
|
+
|
|
247
|
+
The callable `pooledbounds.cli.main(argv)` also returns 2 for these failures but
|
|
248
|
+
never closes or redirects a caller-owned stream. An embedding application owns
|
|
249
|
+
its own later flush and shutdown behavior.
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
Argument help and usage are plain text, without automatic terminal color probes.
|
|
253
|
+
This includes Python 3.14, where the parser and its help formatter each have an
|
|
254
|
+
independent color default. A caller may supply a minimal or closed output stream;
|
|
255
|
+
argument setup does not inspect that stream's terminal or file descriptor. The
|
|
256
|
+
existing output boundary still handles report write/flush failures with exit 2.
|
|
257
|
+
This does not add new handling for every possible help-output failure.
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
# pooledbounds
|
|
2
|
+
|
|
3
|
+
What can pooled p95 actually be when two teams sent histograms with different
|
|
4
|
+
bucket edges? `pooledbounds` keeps the uncertainty instead of making up a
|
|
5
|
+
within-bucket distribution.
|
|
6
|
+
|
|
7
|
+
It computes tight nearest-rank quantile bounds and exact lower/upper counts at
|
|
8
|
+
chosen thresholds. Histograms may have different edges. No shared-edge
|
|
9
|
+
rebucketing, linear interpolation, or expansion into individual observations is
|
|
10
|
+
needed. It also supplies compressed raw-population witnesses attaining both
|
|
11
|
+
threshold count bounds.
|
|
12
|
+
|
|
13
|
+
This is an offline arithmetic tool, not a Prometheus query engine, confidence
|
|
14
|
+
interval estimator, or proof that telemetry is correct.
|
|
15
|
+
|
|
16
|
+
## Example
|
|
17
|
+
|
|
18
|
+
Install from a checked-out copy with `pip install .`, then:
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
pooledbounds examples/mixed-bins.json --quantile 0.95 --threshold 120
|
|
22
|
+
# or
|
|
23
|
+
python -m pooledbounds examples/mixed-bins.json --quantile 0.95
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
The example combines 100 observations in each of two disjoint regions:
|
|
27
|
+
|
|
28
|
+
| Region | Histogram intervals with nonzero counts |
|
|
29
|
+
| --- | --- |
|
|
30
|
+
| A | 90 in (0,100], 10 in (100,200] |
|
|
31
|
+
| B | 50 in (0,150], 50 in (150,300] |
|
|
32
|
+
|
|
33
|
+
The pooled p95 is **strictly greater than 150 and at most 300**. Between 90 and
|
|
34
|
+
150 of the 200 observations are at or below 120, so the exact attainable fraction
|
|
35
|
+
range is [9/20, 3/4]. A point estimate inside those ranges needs an extra
|
|
36
|
+
assumption. Keeping only common finite edges would retain just 0 here and lose
|
|
37
|
+
useful information.
|
|
38
|
+
|
|
39
|
+
## Input contract
|
|
40
|
+
|
|
41
|
+
```json
|
|
42
|
+
{
|
|
43
|
+
"schema": 1,
|
|
44
|
+
"populations": "disjoint-finite-observations",
|
|
45
|
+
"histograms": [
|
|
46
|
+
{"id": "a", "edges": ["0", "100", "200"], "counts": [0, 90, 10, 0]},
|
|
47
|
+
{"id": "b", "edges": ["0", "150", "300"], "counts": [0, 50, 50, 0]}
|
|
48
|
+
]
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- Counts are nonnegative **integers per bucket**, not cumulative counts,
|
|
53
|
+
weights, rates, or values already divided by a sampling factor.
|
|
54
|
+
- Edges are finite decimal strings in strictly increasing order. Scientific
|
|
55
|
+
notation is allowed. Strings avoid silently rounding decimals through binary
|
|
56
|
+
floating point. JSON numbers are not accepted for edges or query values.
|
|
57
|
+
- With edges `[a,b]`, counts describe `(-infinity,a]`, `(a,b]`, and
|
|
58
|
+
`(b,+infinity)`. All observations are finite real numbers. Empty edges with
|
|
59
|
+
one count mean the whole real line. Zero-count buckets are allowed.
|
|
60
|
+
- Histograms must describe disjoint observations. Repeated cumulative snapshots
|
|
61
|
+
of the same counter are **not** separate populations. The declaration is an
|
|
62
|
+
assumption supplied by the caller; the tool cannot verify disjointness or
|
|
63
|
+
distinguish a plausible cumulative count vector from per-bucket counts.
|
|
64
|
+
- Histogram IDs must be unique. Unknown fields, duplicate JSON keys, malformed
|
|
65
|
+
counts, non-increasing edges, and empty pooled populations are invalid.
|
|
66
|
+
- Units must already match. There is no implicit milliseconds/seconds conversion.
|
|
67
|
+
|
|
68
|
+
The input is not an OpenTelemetry or Prometheus export. Convert and check the
|
|
69
|
+
measurement interval, reset behavior, temporality, units and bucket convention
|
|
70
|
+
first. Do not feed `rate()` results as integer counts. `+Inf` observations,
|
|
71
|
+
`-Inf` observations and NaNs are outside this model, even though bins can have
|
|
72
|
+
unbounded endpoints.
|
|
73
|
+
|
|
74
|
+
## Quantile meaning and output
|
|
75
|
+
|
|
76
|
+
`--quantile` is repeatable; its default is 0.5, 0.95, 0.99. For `0 < q <= 1`,
|
|
77
|
+
nearest rank is `ceil(q*N)` in the pooled sorted raw population. The lower
|
|
78
|
+
endpoint is an infimum, **not an attained minimum**. A finite upper endpoint is
|
|
79
|
+
attainable. Unbounded tails are explicit `-infinity`/`+infinity`, never replaced
|
|
80
|
+
with a convenient finite estimate. There is no q=0 convention and no linear
|
|
81
|
+
sample-quantile interpolation.
|
|
82
|
+
|
|
83
|
+
All finite output values use exact rational objects:
|
|
84
|
+
|
|
85
|
+
```json
|
|
86
|
+
{"numerator": "3", "denominator": "4"}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Each quantile includes its rank and the sorted endpoint bucket crossing that
|
|
90
|
+
rank, with counts before and through that bucket. These are arithmetic
|
|
91
|
+
certificates under the input assumptions, not a cryptographic proof or raw-data
|
|
92
|
+
audit. Equal endpoint ties can choose a different provenance bucket if the
|
|
93
|
+
histograms are reordered; numerical bounds are unchanged.
|
|
94
|
+
|
|
95
|
+
`--threshold` is repeatable and asks for the number of observations **<=** that
|
|
96
|
+
value. Both count extrema are attained. Each witness lists one rational value
|
|
97
|
+
and multiplicity for every occupied input bucket. It preserves every supplied
|
|
98
|
+
bucket count, so the report does not expand a count of a billion into a billion
|
|
99
|
+
rows. It does not claim that either synthetic population was actually observed.
|
|
100
|
+
|
|
101
|
+
`input_sha256` binds the parsed document's canonical JSON representation
|
|
102
|
+
(sorted keys, compact separators, ASCII escapes), not its raw file bytes. It is
|
|
103
|
+
not a signature. It does not validate the input assumptions.
|
|
104
|
+
|
|
105
|
+
## Why the bounds are tight
|
|
106
|
+
|
|
107
|
+
Think of each count as repeated unknown values constrained to a bucket
|
|
108
|
+
`(lower,upper]`. For any feasible raw population, sorting the lower endpoints
|
|
109
|
+
bounds its kth value strictly from below; sorting the upper endpoints bounds
|
|
110
|
+
it from above. The kth lower and kth upper endpoints are therefore a valid
|
|
111
|
+
quantile envelope. Moving each unknown value arbitrarily close to its lower
|
|
112
|
+
endpoint approaches the lower bound. Setting values at finite upper endpoints
|
|
113
|
+
attains the finite upper bound. Unbounded endpoints can be approached without
|
|
114
|
+
finite limits. No probabilistic assumption is involved.
|
|
115
|
+
|
|
116
|
+
At threshold t, a bucket is forced below/equal t only if its upper endpoint is
|
|
117
|
+
<=t. A bucket can contribute below/equal t exactly when its lower endpoint is
|
|
118
|
+
<t. Sum these counts independently across the declared disjoint buckets. The
|
|
119
|
+
emitted witnesses construct both extremes with valid finite representatives.
|
|
120
|
+
The strict comparison matters: values in `(t,u]` cannot be <=t.
|
|
121
|
+
|
|
122
|
+
## Python API
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from pooledbounds import analyze, InvalidHistogram, Limits
|
|
126
|
+
|
|
127
|
+
report = analyze(document, quantiles=["0.95"], thresholds=["120"])
|
|
128
|
+
# Invalid or out-of-budget inputs raise InvalidHistogram.
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
The API does not mutate the document, access the environment, import a model,
|
|
132
|
+
open a network connection, or install anything. The CLI reads one UTF-8 JSON
|
|
133
|
+
file or `-` for standard input. Exit 0 means a report was computed in the
|
|
134
|
+
declared model, **not that an SLO passed**. Invalid data or I/O returns INVALID
|
|
135
|
+
JSON and exit 2. Argument syntax errors use argparse stderr and exit 2.
|
|
136
|
+
|
|
137
|
+
## Threshold objectives without interpolation
|
|
138
|
+
|
|
139
|
+
When the question is "at least 95% of observations were <=120", use an explicit
|
|
140
|
+
objective instead of treating a successful arithmetic report as a passing SLO:
|
|
141
|
+
|
|
142
|
+
```sh
|
|
143
|
+
pooledbounds examples/mixed-bins.json --objective 120=.95
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
For this example only 90 to 150 of 200 observations can be <=120. The command
|
|
147
|
+
returns `objective_status: "VIOLATED"` and exit 1: even the largest admissible
|
|
148
|
+
fraction, 3/4, is below .95. The same fixture with `120=.7` is
|
|
149
|
+
`INDETERMINATE` (exit 3), and with `120=.45` is `SATISFIED` (exit 0).
|
|
150
|
+
|
|
151
|
+
Each repeatable `--objective THRESHOLD=MINIMUM_FRACTION` requests a minimum
|
|
152
|
+
fraction of observations **<=** its threshold. Fractions are decimal strings
|
|
153
|
+
between 0 and 1 inclusive, not percentages. Comparisons use exact rational
|
|
154
|
+
arithmetic, with no rounding, tolerance or within-bucket interpolation.
|
|
155
|
+
Objectives cannot be combined with `--quantile` or `--threshold`; ordinary
|
|
156
|
+
queries and their exit behavior are unchanged when no objective is supplied.
|
|
157
|
+
|
|
158
|
+
- `SATISFIED`: the minimum possible good fraction is >= the target. Every
|
|
159
|
+
compatible population meets the objective.
|
|
160
|
+
- `VIOLATED`: the maximum possible good fraction is < the target. No compatible
|
|
161
|
+
population meets the objective.
|
|
162
|
+
- `INDETERMINATE`: some compatible populations meet it and some do not. A
|
|
163
|
+
fraction whose upper bound equals the target is not a proven violation.
|
|
164
|
+
|
|
165
|
+
For several objectives, all must hold: any proven violation returns 1;
|
|
166
|
+
otherwise any indeterminate objective returns 3; otherwise the command returns
|
|
167
|
+
0. These minimum-fraction objectives are jointly compatible whenever each is
|
|
168
|
+
individually possible: putting values sufficiently close to each bucket's lower
|
|
169
|
+
endpoint attains all queried maximum counts simultaneously. Invalid input,
|
|
170
|
+
conflicting options and output failure return 2, taking priority over a computed
|
|
171
|
+
verdict. A zero observation total is invalid, not a vacuous pass.
|
|
172
|
+
|
|
173
|
+
The JSON retains the ordinary model status, input digest, total count and
|
|
174
|
+
threshold evidence, including count/fraction extrema and compressed witnesses.
|
|
175
|
+
`objectives` adds each exact target and a zero-based `threshold_index` into
|
|
176
|
+
`thresholds`, plus its verdict. `objective_status` combines the verdicts. Witnesses
|
|
177
|
+
are synthetic compatible populations, not measured requests.
|
|
178
|
+
|
|
179
|
+
```python
|
|
180
|
+
from pooledbounds import evaluate_objectives
|
|
181
|
+
|
|
182
|
+
report = evaluate_objectives(document, [
|
|
183
|
+
{"threshold": "120", "minimum_fraction": ".95"},
|
|
184
|
+
])
|
|
185
|
+
assert report["objective_status"] in {"SATISFIED", "VIOLATED", "INDETERMINATE"}
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
This is a decision **inside the declared input model**, not a production SLO
|
|
189
|
+
certification, statistical confidence statement, telemetry-completeness check,
|
|
190
|
+
or live alert. Units, windows, disjointness and correct per-bucket integer counts
|
|
191
|
+
remain the caller's responsibility. Prometheus cumulative snapshots, rates and
|
|
192
|
+
reset handling are still outside the accepted input format. Existing monitoring
|
|
193
|
+
tools are preferable for live SLOs; this mode answers what an already exported,
|
|
194
|
+
unequal-bin population can prove without inventing hidden observations.
|
|
195
|
+
|
|
196
|
+
## Admission limits
|
|
197
|
+
|
|
198
|
+
Defaults: 1,000 histograms, 100,000 total buckets including empty ones,
|
|
199
|
+
1,000 queries, 128 characters per decimal, exponent magnitude <=1,000,
|
|
200
|
+
and total count <=10^18. The CLI reads at most 8 MiB plus one byte before
|
|
201
|
+
refusing a larger input. API callers already hold their documents in memory.
|
|
202
|
+
|
|
203
|
+
`Limits` can adjust histogram, bucket, number-character, total-count and
|
|
204
|
+
query/bucket-work caps. The work cap defaults to 1,000,000 units:
|
|
205
|
+
`occupied_buckets * (quantile_queries + 2 * threshold_queries)`.
|
|
206
|
+
This also bounds the number of threshold witness rows emitted. Endpoints are
|
|
207
|
+
sorted once per side; cumulative integer counts then let each quantile rank
|
|
208
|
+
use binary search instead of rescanning every occupied bucket. Equal endpoint
|
|
209
|
+
ties retain input order and the same bucket certificates. The two cumulative
|
|
210
|
+
count lists add one integer per occupied bucket per side. Threshold witnesses
|
|
211
|
+
still scan buckets, and the original admission-work formula is unchanged.
|
|
212
|
+
Count size does not cause per-observation allocation.
|
|
213
|
+
These are admission limits, not hard RAM, encoded-output-size or CPU guarantees.
|
|
214
|
+
Large rational values and caller-chosen larger caps can still be expensive.
|
|
215
|
+
|
|
216
|
+
## Evidence and scope
|
|
217
|
+
|
|
218
|
+
See [EVIDENCE.md](EVIDENCE.md) for the practical problem and comparison with
|
|
219
|
+
existing histogram tools. This applies elementary order-statistic bounds to a
|
|
220
|
+
specific offline workflow; it does not claim a new statistical method or that
|
|
221
|
+
no other implementation exists. Existing native histogram/sketch tools are
|
|
222
|
+
usually the better choice when you control future instrumentation.
|
|
223
|
+
|
|
224
|
+
Tests include enumeration of every raw population in small integer/half-integer
|
|
225
|
+
fixtures, independent checks of witness bucket membership and counts, exact
|
|
226
|
+
large ranks, unbounded tails, invalid inputs and resource admission. Synthetic
|
|
227
|
+
tests are not evidence of adoption or production accuracy.
|
|
228
|
+
|
|
229
|
+
## Output failures
|
|
230
|
+
|
|
231
|
+
The module and installed command return exit 2 when stdout cannot be written or
|
|
232
|
+
flushed, including a closed pipe or a full device. Already-written partial bytes
|
|
233
|
+
cannot be retracted, so check the exit status before using a report. The process
|
|
234
|
+
runner redirects a failed stdout to the null device before shutdown, preventing
|
|
235
|
+
Python's second flush from replacing exit 2 with exit 120.
|
|
236
|
+
|
|
237
|
+
The callable `pooledbounds.cli.main(argv)` also returns 2 for these failures but
|
|
238
|
+
never closes or redirects a caller-owned stream. An embedding application owns
|
|
239
|
+
its own later flush and shutdown behavior.
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
Argument help and usage are plain text, without automatic terminal color probes.
|
|
243
|
+
This includes Python 3.14, where the parser and its help formatter each have an
|
|
244
|
+
independent color default. A caller may supply a minimal or closed output stream;
|
|
245
|
+
argument setup does not inspect that stream's terminal or file descriptor. The
|
|
246
|
+
existing output boundary still handles report write/flush failures with exit 2.
|
|
247
|
+
This does not add new handling for every possible help-output failure.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
name = "pooledbounds"
|
|
8
|
+
version = "0.2.0"
|
|
9
|
+
description = "Bounds, not interpolated guesses, for pooled unequal-bin histograms"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
|
|
13
|
+
[project.scripts]
|
|
14
|
+
pooledbounds = "pooledbounds.cli:entrypoint"
|
|
15
|
+
|
|
16
|
+
[tool.setuptools.packages.find]
|
|
17
|
+
where = ["src"]
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Offline JSON histogram envelopes. Does not fetch, install, or query a server."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import inspect
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from .core import InvalidHistogram, analyze
|
|
8
|
+
from .objectives import evaluate_objectives
|
|
9
|
+
|
|
10
|
+
MAX_INPUT_BYTES = 8 * 1024 * 1024
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _object(pairs):
|
|
14
|
+
result = {}
|
|
15
|
+
for key, value in pairs:
|
|
16
|
+
if key in result:
|
|
17
|
+
raise InvalidHistogram('duplicate JSON key')
|
|
18
|
+
result[key] = value
|
|
19
|
+
return result
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _PlainFormatter(argparse.HelpFormatter):
|
|
24
|
+
def __init__(self, *args, **kwargs):
|
|
25
|
+
# 3.14 creates formatters with their own color=True default before
|
|
26
|
+
# applying the parser's color option. Disable both independent probes.
|
|
27
|
+
if 'color' in inspect.signature(argparse.HelpFormatter).parameters:
|
|
28
|
+
kwargs['color'] = False
|
|
29
|
+
super().__init__(*args, **kwargs)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _execute(argv=None):
|
|
33
|
+
# Python 3.14 argparse probes stdout for color support during setup, even
|
|
34
|
+
# for ordinary report commands. Embedded callers may supply closed/minimal
|
|
35
|
+
# streams; the CLI output boundary, not color discovery, must handle them.
|
|
36
|
+
options = {'color': False} if 'color' in inspect.signature(argparse.ArgumentParser).parameters else {}
|
|
37
|
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=_PlainFormatter, **options)
|
|
38
|
+
parser.add_argument('input', help='JSON file, or - for standard input')
|
|
39
|
+
parser.add_argument('--quantile', action='append', help='decimal in (0,1]; repeatable')
|
|
40
|
+
parser.add_argument('--threshold', action='append', default=[], help='finite decimal; repeatable')
|
|
41
|
+
parser.add_argument('--objective', action='append', help='THRESHOLD=MINIMUM_FRACTION; repeatable; exclusive with query options')
|
|
42
|
+
args = parser.parse_args(argv)
|
|
43
|
+
try:
|
|
44
|
+
if args.input == '-':
|
|
45
|
+
if sys.stdin is None:
|
|
46
|
+
raise InvalidHistogram('standard input is unavailable')
|
|
47
|
+
raw = sys.stdin.buffer.read(MAX_INPUT_BYTES + 1)
|
|
48
|
+
else:
|
|
49
|
+
with open(args.input, 'rb') as stream:
|
|
50
|
+
raw = stream.read(MAX_INPUT_BYTES + 1)
|
|
51
|
+
if len(raw) > MAX_INPUT_BYTES:
|
|
52
|
+
raise InvalidHistogram('input byte limit exceeded')
|
|
53
|
+
document = json.loads(raw.decode('utf-8'), object_pairs_hook=_object)
|
|
54
|
+
if args.objective is not None:
|
|
55
|
+
if args.quantile is not None or args.threshold:
|
|
56
|
+
raise InvalidHistogram('objectives cannot be combined with quantile or threshold options')
|
|
57
|
+
objectives = []
|
|
58
|
+
for value in args.objective:
|
|
59
|
+
if value.count('=') != 1:
|
|
60
|
+
raise InvalidHistogram('objective must be THRESHOLD=MINIMUM_FRACTION')
|
|
61
|
+
threshold, fraction = value.split('=')
|
|
62
|
+
objectives.append({'threshold': threshold, 'minimum_fraction': fraction})
|
|
63
|
+
result = evaluate_objectives(document, objectives)
|
|
64
|
+
code = {'SATISFIED': 0, 'VIOLATED': 1, 'INDETERMINATE': 3}[result['objective_status']]
|
|
65
|
+
else:
|
|
66
|
+
result = analyze(document, quantiles=args.quantile if args.quantile is not None else
|
|
67
|
+
['0.5', '0.95', '0.99'], thresholds=args.threshold)
|
|
68
|
+
code = 0
|
|
69
|
+
except (InvalidHistogram, ValueError, OSError, UnicodeError, RecursionError) as exc:
|
|
70
|
+
result, code = {'schema': 1, 'status': 'INVALID', 'error': str(exc)}, 2
|
|
71
|
+
try:
|
|
72
|
+
sys.stdout.write(json.dumps(result, sort_keys=True) + '\n')
|
|
73
|
+
sys.stdout.flush()
|
|
74
|
+
except (OSError, ValueError, AttributeError):
|
|
75
|
+
return 2, True
|
|
76
|
+
return code, False
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def main(argv=None):
|
|
80
|
+
"""Run without closing or redirecting caller-owned output streams."""
|
|
81
|
+
return _execute(argv)[0]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def entrypoint():
|
|
85
|
+
"""Process runner: stop a failed stdout from failing again at shutdown."""
|
|
86
|
+
code, output_failed = _execute()
|
|
87
|
+
if output_failed:
|
|
88
|
+
# An unsuccessful flush can leave bytes buffered. Python retries at
|
|
89
|
+
# interpreter shutdown and overrides SystemExit(2) with exit 120.
|
|
90
|
+
# Only the executable runner may redirect its process-owned stdout.
|
|
91
|
+
try:
|
|
92
|
+
stdout_fd = sys.stdout.fileno()
|
|
93
|
+
null_fd = os.open(os.devnull, os.O_WRONLY)
|
|
94
|
+
try:
|
|
95
|
+
os.dup2(null_fd, stdout_fd)
|
|
96
|
+
finally:
|
|
97
|
+
if null_fd != stdout_fd:
|
|
98
|
+
os.close(null_fd)
|
|
99
|
+
except (OSError, ValueError, AttributeError):
|
|
100
|
+
# Custom process streams need not expose a working descriptor.
|
|
101
|
+
sys.stdout = open(os.devnull, 'w')
|
|
102
|
+
return code
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
if __name__ == '__main__':
|
|
106
|
+
sys.exit(entrypoint())
|