streamparity 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.
- streamparity-0.2.0/LICENSE +22 -0
- streamparity-0.2.0/PKG-INFO +125 -0
- streamparity-0.2.0/README.md +92 -0
- streamparity-0.2.0/pyproject.toml +63 -0
- streamparity-0.2.0/setup.cfg +4 -0
- streamparity-0.2.0/src/streamparity/__init__.py +10 -0
- streamparity-0.2.0/src/streamparity/core.py +254 -0
- streamparity-0.2.0/src/streamparity.egg-info/PKG-INFO +125 -0
- streamparity-0.2.0/src/streamparity.egg-info/SOURCES.txt +12 -0
- streamparity-0.2.0/src/streamparity.egg-info/dependency_links.txt +1 -0
- streamparity-0.2.0/src/streamparity.egg-info/requires.txt +6 -0
- streamparity-0.2.0/src/streamparity.egg-info/top_level.txt +1 -0
- streamparity-0.2.0/tests/test_core.py +85 -0
- streamparity-0.2.0/tests/test_extended.py +75 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jaskaran Singh
|
|
4
|
+
Copyright (c) 2026 StreamParity contributors
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: streamparity
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Research-to-production consistency testing for numerical and streaming pipelines
|
|
5
|
+
Author: Jaskaran Singh
|
|
6
|
+
Maintainer: Jaskaran Singh
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Project-URL: Homepage, https://github.com/jaskaran04/streamparity
|
|
9
|
+
Project-URL: Repository, https://github.com/jaskaran04/streamparity
|
|
10
|
+
Project-URL: Issues, https://github.com/jaskaran04/streamparity/issues
|
|
11
|
+
Project-URL: Documentation, https://github.com/jaskaran04/streamparity#readme
|
|
12
|
+
Keywords: quantitative-finance,algorithmic-trading,backtesting,lookahead-bias,streaming,numerical-computing,testing,machine-learning,time-series,reproducibility
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
16
|
+
Classifier: Intended Audience :: Science/Research
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Operating System :: OS Independent
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering
|
|
22
|
+
Classifier: Topic :: Software Development :: Testing
|
|
23
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: numpy>=1.24
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
30
|
+
Requires-Dist: build; extra == "dev"
|
|
31
|
+
Requires-Dist: twine; extra == "dev"
|
|
32
|
+
Dynamic: license-file
|
|
33
|
+
|
|
34
|
+
# StreamParity
|
|
35
|
+
|
|
36
|
+
**Test research-to-production consistency in numerical streaming pipelines.**
|
|
37
|
+
|
|
38
|
+
StreamParity is an offline testing toolkit for comparing batch calculations with incremental, stateful implementations. Applications include quantitative trading, numerical risk models, sensor processing and production ML. It is currently an early-stage Python package, not a certified production validation system.
|
|
39
|
+
|
|
40
|
+
## Install from source
|
|
41
|
+
|
|
42
|
+
Requires Python 3.10+ and NumPy. From the repository root:
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
python -m pip install -e ".[dev]"
|
|
46
|
+
python -m pytest -q
|
|
47
|
+
python examples/trading_replay.py
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The name `streamparity` is proposed; public PyPI publication is not yet confirmed.
|
|
51
|
+
|
|
52
|
+
## Quick start
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
import numpy as np
|
|
56
|
+
from streamparity import audit
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def streaming():
|
|
60
|
+
total = 0.0
|
|
61
|
+
|
|
62
|
+
def update(chunk):
|
|
63
|
+
nonlocal total
|
|
64
|
+
out = total + np.cumsum(chunk)
|
|
65
|
+
total = out[-1]
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
return update
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
report = audit(np.cumsum, streaming, [1., -2., 3., -1.],
|
|
72
|
+
random_trials=5, seed=42, max_chunk=3,
|
|
73
|
+
decision=lambda y: y > 0)
|
|
74
|
+
print(report.summary())
|
|
75
|
+
report.assert_passed() # raises AssertionError if a check fails
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Checks
|
|
79
|
+
|
|
80
|
+
| Function | Comparison |
|
|
81
|
+
| --- | --- |
|
|
82
|
+
| `check_batch_stream` | Batch output vs single-row incremental replay |
|
|
83
|
+
| `check_chunks` | Fixed-size partitions vs single-row replay |
|
|
84
|
+
| `check_lookahead` | Full-run historical outputs vs prefix-only executions |
|
|
85
|
+
| `check_random_chunks` | Seeded random partitions vs single-row replay |
|
|
86
|
+
| `check_restart` | Uninterrupted replay vs checkpoint/restart replay |
|
|
87
|
+
| `check_decisions` | Exact discrete decisions from batch vs single-row streaming outputs |
|
|
88
|
+
| `audit` | Combined checks; optional random, restart and decision checks |
|
|
89
|
+
|
|
90
|
+
`AuditReport` provides `.passed`, `.checks`, `.summary()`, `.assert_passed()`, `.to_dict()` and `.to_json()`. Each check reports its scenario, status, count of mismatched rows and zero-based first mismatch. Shape mismatches are reported separately (row mismatch count is zero and index is null). No raw inputs or output values are included in reports. User-selected scenarios are not exhaustive.
|
|
91
|
+
|
|
92
|
+
### Checkpoint recovery
|
|
93
|
+
|
|
94
|
+
A checkpoint callback serializes the updater's state to immutable bytes. A restore callback loads those bytes into a fresh updater in place. Test the same serialization callbacks used by the real application whenever possible.
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from streamparity import check_restart
|
|
98
|
+
|
|
99
|
+
results = check_restart(
|
|
100
|
+
streaming_factory, data,
|
|
101
|
+
checkpoint=lambda updater: updater.save_state(),
|
|
102
|
+
restore=lambda updater, state: updater.load_state(state),
|
|
103
|
+
points=(10, 50), # restart after this many consumed rows
|
|
104
|
+
)
|
|
105
|
+
assert all(r.passed for r in results)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
See `examples/trading_replay.py` for a complete runnable implementation and an intentional recovery failure. This simulates state restoration within a process; it does not kill processes, simulate network failures or verify durability on disk.
|
|
109
|
+
|
|
110
|
+
### Contracts and numerical semantics
|
|
111
|
+
|
|
112
|
+
- `batch(data)` is deterministic and stateless or freshly reset; `streaming()` returns a fresh stateful callable `update(chunk)` for each replay. State is retained across calls to that updater only.
|
|
113
|
+
- Axis 0 is time. Both transforms return one nonempty numerical output row per input row, in identical order. Input and output arrays are copied to isolate ordinary in-place mutations.
|
|
114
|
+
- Real numeric and boolean arrays are supported. Inputs must be nonempty; lookahead, restart and combined audits require at least two rows.
|
|
115
|
+
- Integer/boolean pairs compare exactly; floating or mixed outputs use NumPy `isclose(actual, expected, rtol, atol, equal_nan)`. Mixed integer/floating comparisons may lose precision; return matching discrete dtypes for exact decisions. Matching NaNs are equal by default; set `equal_nan=False` to reject them. Equal infinities compare equal.
|
|
116
|
+
- `decision(outputs)` must be a deterministic row-wise mapping to integer or boolean labels. It is evaluated separately on complete batch and incremental output arrays and compared exactly, not with numerical tolerances. The library cannot verify causality of the user-supplied decision function.
|
|
117
|
+
- Exceptions from user code propagate. Random trials use a nonnegative integer seed and bounded random partitions; a seed and scenario identify a replay within the same NumPy environment.
|
|
118
|
+
|
|
119
|
+
### Limits
|
|
120
|
+
|
|
121
|
+
Passing tests are evidence on the supplied data, scenarios and tolerances, not proof of equivalence, causality or profitable trading. Future-derived features, externally fitted parameters and untested prefixes can evade lookahead checks. Fixed and random partitions preserve input ordering. No asynchronous or late-event replay, timestamp alignment, dataframe metadata, stochastic transform support, distributed execution, or process-crash simulation. The current implementation replays and stores complete outputs; benchmark before large-scale use.
|
|
122
|
+
|
|
123
|
+
## Release preparation
|
|
124
|
+
|
|
125
|
+
See `RELEASING.md`. MIT licence is proposed; review the copyright attribution before distributing. Contributions should include regression tests.
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# StreamParity
|
|
2
|
+
|
|
3
|
+
**Test research-to-production consistency in numerical streaming pipelines.**
|
|
4
|
+
|
|
5
|
+
StreamParity is an offline testing toolkit for comparing batch calculations with incremental, stateful implementations. Applications include quantitative trading, numerical risk models, sensor processing and production ML. It is currently an early-stage Python package, not a certified production validation system.
|
|
6
|
+
|
|
7
|
+
## Install from source
|
|
8
|
+
|
|
9
|
+
Requires Python 3.10+ and NumPy. From the repository root:
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
python -m pip install -e ".[dev]"
|
|
13
|
+
python -m pytest -q
|
|
14
|
+
python examples/trading_replay.py
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The name `streamparity` is proposed; public PyPI publication is not yet confirmed.
|
|
18
|
+
|
|
19
|
+
## Quick start
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
import numpy as np
|
|
23
|
+
from streamparity import audit
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def streaming():
|
|
27
|
+
total = 0.0
|
|
28
|
+
|
|
29
|
+
def update(chunk):
|
|
30
|
+
nonlocal total
|
|
31
|
+
out = total + np.cumsum(chunk)
|
|
32
|
+
total = out[-1]
|
|
33
|
+
return out
|
|
34
|
+
|
|
35
|
+
return update
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
report = audit(np.cumsum, streaming, [1., -2., 3., -1.],
|
|
39
|
+
random_trials=5, seed=42, max_chunk=3,
|
|
40
|
+
decision=lambda y: y > 0)
|
|
41
|
+
print(report.summary())
|
|
42
|
+
report.assert_passed() # raises AssertionError if a check fails
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Checks
|
|
46
|
+
|
|
47
|
+
| Function | Comparison |
|
|
48
|
+
| --- | --- |
|
|
49
|
+
| `check_batch_stream` | Batch output vs single-row incremental replay |
|
|
50
|
+
| `check_chunks` | Fixed-size partitions vs single-row replay |
|
|
51
|
+
| `check_lookahead` | Full-run historical outputs vs prefix-only executions |
|
|
52
|
+
| `check_random_chunks` | Seeded random partitions vs single-row replay |
|
|
53
|
+
| `check_restart` | Uninterrupted replay vs checkpoint/restart replay |
|
|
54
|
+
| `check_decisions` | Exact discrete decisions from batch vs single-row streaming outputs |
|
|
55
|
+
| `audit` | Combined checks; optional random, restart and decision checks |
|
|
56
|
+
|
|
57
|
+
`AuditReport` provides `.passed`, `.checks`, `.summary()`, `.assert_passed()`, `.to_dict()` and `.to_json()`. Each check reports its scenario, status, count of mismatched rows and zero-based first mismatch. Shape mismatches are reported separately (row mismatch count is zero and index is null). No raw inputs or output values are included in reports. User-selected scenarios are not exhaustive.
|
|
58
|
+
|
|
59
|
+
### Checkpoint recovery
|
|
60
|
+
|
|
61
|
+
A checkpoint callback serializes the updater's state to immutable bytes. A restore callback loads those bytes into a fresh updater in place. Test the same serialization callbacks used by the real application whenever possible.
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from streamparity import check_restart
|
|
65
|
+
|
|
66
|
+
results = check_restart(
|
|
67
|
+
streaming_factory, data,
|
|
68
|
+
checkpoint=lambda updater: updater.save_state(),
|
|
69
|
+
restore=lambda updater, state: updater.load_state(state),
|
|
70
|
+
points=(10, 50), # restart after this many consumed rows
|
|
71
|
+
)
|
|
72
|
+
assert all(r.passed for r in results)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
See `examples/trading_replay.py` for a complete runnable implementation and an intentional recovery failure. This simulates state restoration within a process; it does not kill processes, simulate network failures or verify durability on disk.
|
|
76
|
+
|
|
77
|
+
### Contracts and numerical semantics
|
|
78
|
+
|
|
79
|
+
- `batch(data)` is deterministic and stateless or freshly reset; `streaming()` returns a fresh stateful callable `update(chunk)` for each replay. State is retained across calls to that updater only.
|
|
80
|
+
- Axis 0 is time. Both transforms return one nonempty numerical output row per input row, in identical order. Input and output arrays are copied to isolate ordinary in-place mutations.
|
|
81
|
+
- Real numeric and boolean arrays are supported. Inputs must be nonempty; lookahead, restart and combined audits require at least two rows.
|
|
82
|
+
- Integer/boolean pairs compare exactly; floating or mixed outputs use NumPy `isclose(actual, expected, rtol, atol, equal_nan)`. Mixed integer/floating comparisons may lose precision; return matching discrete dtypes for exact decisions. Matching NaNs are equal by default; set `equal_nan=False` to reject them. Equal infinities compare equal.
|
|
83
|
+
- `decision(outputs)` must be a deterministic row-wise mapping to integer or boolean labels. It is evaluated separately on complete batch and incremental output arrays and compared exactly, not with numerical tolerances. The library cannot verify causality of the user-supplied decision function.
|
|
84
|
+
- Exceptions from user code propagate. Random trials use a nonnegative integer seed and bounded random partitions; a seed and scenario identify a replay within the same NumPy environment.
|
|
85
|
+
|
|
86
|
+
### Limits
|
|
87
|
+
|
|
88
|
+
Passing tests are evidence on the supplied data, scenarios and tolerances, not proof of equivalence, causality or profitable trading. Future-derived features, externally fitted parameters and untested prefixes can evade lookahead checks. Fixed and random partitions preserve input ordering. No asynchronous or late-event replay, timestamp alignment, dataframe metadata, stochastic transform support, distributed execution, or process-crash simulation. The current implementation replays and stores complete outputs; benchmark before large-scale use.
|
|
89
|
+
|
|
90
|
+
## Release preparation
|
|
91
|
+
|
|
92
|
+
See `RELEASING.md`. MIT licence is proposed; review the copyright attribution before distributing. Contributions should include regression tests.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "streamparity"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Research-to-production consistency testing for numerical and streaming pipelines"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
dependencies = ["numpy>=1.24"]
|
|
14
|
+
|
|
15
|
+
authors = [
|
|
16
|
+
{name = "Jaskaran Singh"}
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
maintainers = [
|
|
20
|
+
{name = "Jaskaran Singh"}
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
keywords = [
|
|
24
|
+
"quantitative-finance",
|
|
25
|
+
"algorithmic-trading",
|
|
26
|
+
"backtesting",
|
|
27
|
+
"lookahead-bias",
|
|
28
|
+
"streaming",
|
|
29
|
+
"numerical-computing",
|
|
30
|
+
"testing",
|
|
31
|
+
"machine-learning",
|
|
32
|
+
"time-series",
|
|
33
|
+
"reproducibility"
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
classifiers = [
|
|
37
|
+
"Development Status :: 3 - Alpha",
|
|
38
|
+
"Intended Audience :: Developers",
|
|
39
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
40
|
+
"Intended Audience :: Science/Research",
|
|
41
|
+
"Programming Language :: Python :: 3",
|
|
42
|
+
"Programming Language :: Python :: 3.11",
|
|
43
|
+
"Programming Language :: Python :: 3.13",
|
|
44
|
+
"Operating System :: OS Independent",
|
|
45
|
+
"Topic :: Scientific/Engineering",
|
|
46
|
+
"Topic :: Software Development :: Testing",
|
|
47
|
+
"Topic :: Office/Business :: Financial"
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
[project.urls]
|
|
51
|
+
Homepage = "https://github.com/jaskaran04/streamparity"
|
|
52
|
+
Repository = "https://github.com/jaskaran04/streamparity"
|
|
53
|
+
Issues = "https://github.com/jaskaran04/streamparity/issues"
|
|
54
|
+
Documentation = "https://github.com/jaskaran04/streamparity#readme"
|
|
55
|
+
|
|
56
|
+
[project.optional-dependencies]
|
|
57
|
+
dev = ["pytest>=7", "build", "twine"]
|
|
58
|
+
|
|
59
|
+
[tool.setuptools.packages.find]
|
|
60
|
+
where = ["src"]
|
|
61
|
+
|
|
62
|
+
[tool.pytest.ini_options]
|
|
63
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Consistency checks for deterministic numerical pipelines."""
|
|
2
|
+
from .core import (
|
|
3
|
+
AuditReport, CheckResult, audit, check_batch_stream, check_chunks,
|
|
4
|
+
check_lookahead, check_random_chunks, check_restart, check_decisions,
|
|
5
|
+
)
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"AuditReport", "CheckResult", "audit", "check_batch_stream", "check_chunks",
|
|
9
|
+
"check_lookahead", "check_random_chunks", "check_restart", "check_decisions",
|
|
10
|
+
]
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""One output row per input row; fresh state per replay."""
|
|
2
|
+
from dataclasses import asdict, dataclass
|
|
3
|
+
import json
|
|
4
|
+
from typing import Callable, Iterable
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
Transform = Callable[[np.ndarray], np.ndarray]
|
|
8
|
+
Factory = Callable[[], Transform]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class CheckResult:
|
|
13
|
+
name: str
|
|
14
|
+
scenario: str
|
|
15
|
+
passed: bool
|
|
16
|
+
mismatched_rows: int
|
|
17
|
+
first_mismatch: int | None
|
|
18
|
+
detail: str = ""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class AuditReport:
|
|
23
|
+
checks: tuple[CheckResult, ...]
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def passed(self) -> bool:
|
|
27
|
+
return all(check.passed for check in self.checks)
|
|
28
|
+
|
|
29
|
+
def summary(self) -> str:
|
|
30
|
+
lines = [f"{'PASS' if c.passed else 'FAIL'} {c.name} [{c.scenario}]"
|
|
31
|
+
+ (f": {c.detail}" if c.detail else "") for c in self.checks]
|
|
32
|
+
return "\n".join(lines + [f"{sum(c.passed for c in self.checks)}/{len(self.checks)} passed"])
|
|
33
|
+
|
|
34
|
+
def to_dict(self) -> dict:
|
|
35
|
+
"""Return JSON-compatible results (no raw customer data)."""
|
|
36
|
+
return {"passed": self.passed, "checks": [asdict(c) for c in self.checks]}
|
|
37
|
+
|
|
38
|
+
def to_json(self, *, indent=2) -> str:
|
|
39
|
+
return json.dumps(self.to_dict(), indent=indent)
|
|
40
|
+
|
|
41
|
+
def assert_passed(self) -> None:
|
|
42
|
+
if not self.passed:
|
|
43
|
+
raise AssertionError(self.summary())
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _data(data):
|
|
47
|
+
x = np.array(data, copy=True)
|
|
48
|
+
if x.ndim == 0 or len(x) == 0:
|
|
49
|
+
raise ValueError("data must have a nonempty time axis (axis 0)")
|
|
50
|
+
if x.dtype.kind not in "biuf":
|
|
51
|
+
raise TypeError("data must be real numeric or boolean")
|
|
52
|
+
return x
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _output(value, n):
|
|
56
|
+
y = np.array(value, copy=True)
|
|
57
|
+
if y.ndim == 0 or len(y) != n or y.size == 0:
|
|
58
|
+
raise ValueError("transform must return one nonempty output row per input row")
|
|
59
|
+
if y.dtype.kind not in "biuf":
|
|
60
|
+
raise TypeError("outputs must be real numeric or boolean")
|
|
61
|
+
return y
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _tolerances(rtol, atol):
|
|
65
|
+
if not np.isfinite(rtol) or not np.isfinite(atol) or rtol < 0 or atol < 0:
|
|
66
|
+
raise ValueError("tolerances must be finite and nonnegative")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _compare(name, scenario, expected, actual, rtol, atol, equal_nan):
|
|
70
|
+
if expected.shape != actual.shape:
|
|
71
|
+
return CheckResult(name, scenario, False, 0, None,
|
|
72
|
+
f"shape mismatch: {expected.shape} vs {actual.shape}")
|
|
73
|
+
# Exact comparisons for discrete outputs avoid lossy integer-to-float conversion.
|
|
74
|
+
if expected.dtype.kind in "biu" and actual.dtype.kind in "biu":
|
|
75
|
+
if expected.dtype.kind == actual.dtype.kind or "u" not in (expected.dtype.kind, actual.dtype.kind):
|
|
76
|
+
same = expected == actual
|
|
77
|
+
else:
|
|
78
|
+
same = expected.astype(object) == actual.astype(object)
|
|
79
|
+
else:
|
|
80
|
+
same = np.isclose(actual, expected, rtol=rtol, atol=atol, equal_nan=equal_nan)
|
|
81
|
+
rows = np.all(same.reshape(len(expected), -1), axis=1)
|
|
82
|
+
bad = np.flatnonzero(~rows)
|
|
83
|
+
return CheckResult(name, scenario, not len(bad), len(bad),
|
|
84
|
+
int(bad[0]) if len(bad) else None,
|
|
85
|
+
f"{len(bad)} mismatched rows; first at {bad[0]}" if len(bad) else "")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _replay(factory, x, size):
|
|
89
|
+
return _run_schedule(factory(), x, (min(size, len(x)-i) for i in range(0, len(x), size)))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _run_schedule(update, x, schedule):
|
|
93
|
+
outputs = []
|
|
94
|
+
start = 0
|
|
95
|
+
for size in schedule:
|
|
96
|
+
chunk = x[start:start+size].copy()
|
|
97
|
+
outputs.append(_output(update(chunk), len(chunk)))
|
|
98
|
+
start += size
|
|
99
|
+
if start != len(x):
|
|
100
|
+
raise ValueError("schedule must cover all rows exactly")
|
|
101
|
+
return np.concatenate(outputs, axis=0)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def check_batch_stream(batch: Transform, streaming: Factory, data, *,
|
|
105
|
+
rtol=1e-7, atol=1e-10, equal_nan=True) -> CheckResult:
|
|
106
|
+
"""Compare a fresh batch execution with fresh one-row-at-a-time state."""
|
|
107
|
+
x = _data(data)
|
|
108
|
+
_tolerances(rtol, atol)
|
|
109
|
+
expected = _output(batch(x.copy()), len(x))
|
|
110
|
+
actual = _replay(streaming, x, 1)
|
|
111
|
+
return _compare("batch_stream", "size=1", expected, actual, rtol, atol, equal_nan)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def check_chunks(streaming: Factory, data, *, sizes: Iterable[int] = (2, 8, 32),
|
|
115
|
+
rtol=1e-7, atol=1e-10, equal_nan=True) -> tuple[CheckResult, ...]:
|
|
116
|
+
"""Compare fresh streaming replays with the one-row baseline."""
|
|
117
|
+
x = _data(data)
|
|
118
|
+
_tolerances(rtol, atol)
|
|
119
|
+
sizes = tuple(sizes)
|
|
120
|
+
if not sizes or any(isinstance(s, bool) or not isinstance(s, (int, np.integer)) or s < 1 for s in sizes):
|
|
121
|
+
raise ValueError("sizes must contain positive integers")
|
|
122
|
+
baseline = _replay(streaming, x, 1)
|
|
123
|
+
return tuple(_compare("chunks", f"size={s}", baseline, _replay(streaming, x, s),
|
|
124
|
+
rtol, atol, equal_nan) for s in sizes)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def check_lookahead(batch: Transform, data, *, prefixes: Iterable[int] | None = None,
|
|
128
|
+
rtol=1e-7, atol=1e-10, equal_nan=True) -> tuple[CheckResult, ...]:
|
|
129
|
+
"""Compare prefix-only outputs with matching rows from a full run.
|
|
130
|
+
|
|
131
|
+
A pass is evidence on tested prefixes, not a proof of causality.
|
|
132
|
+
"""
|
|
133
|
+
x = _data(data)
|
|
134
|
+
_tolerances(rtol, atol)
|
|
135
|
+
if len(x) < 2:
|
|
136
|
+
raise ValueError("lookahead checks require at least two rows")
|
|
137
|
+
if prefixes is None:
|
|
138
|
+
prefixes = sorted({1, len(x)//4, len(x)//2, 3*len(x)//4, len(x)-1} - {0})
|
|
139
|
+
prefixes = tuple(prefixes)
|
|
140
|
+
if not prefixes or any(isinstance(p, bool) or not isinstance(p, (int, np.integer)) or not 1 <= p < len(x) for p in prefixes):
|
|
141
|
+
raise ValueError("prefixes must be integers between 1 and len(data)-1")
|
|
142
|
+
full = _output(batch(x.copy()), len(x))
|
|
143
|
+
return tuple(_compare("lookahead", f"prefix={p}", full[:p],
|
|
144
|
+
_output(batch(x[:p].copy()), p), rtol, atol, equal_nan)
|
|
145
|
+
for p in prefixes)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def audit(batch: Transform, streaming: Factory, data, *, sizes=(2, 8, 32),
|
|
149
|
+
prefixes=None, rtol=1e-7, atol=1e-10, equal_nan=True,
|
|
150
|
+
random_trials=0, seed=0, max_chunk=32, decision=None,
|
|
151
|
+
checkpoint=None, restore=None, restart_points=None) -> AuditReport:
|
|
152
|
+
"""Run all three checks; user transform exceptions propagate to the caller."""
|
|
153
|
+
opts = dict(rtol=rtol, atol=atol, equal_nan=equal_nan)
|
|
154
|
+
checks = [check_batch_stream(batch, streaming, data, **opts),
|
|
155
|
+
*check_chunks(streaming, data, sizes=sizes, **opts),
|
|
156
|
+
*check_lookahead(batch, data, prefixes=prefixes, **opts)]
|
|
157
|
+
if isinstance(random_trials, bool) or not isinstance(random_trials, (int, np.integer)) or random_trials < 0:
|
|
158
|
+
raise ValueError("random_trials must be a nonnegative integer")
|
|
159
|
+
if random_trials:
|
|
160
|
+
checks.extend(check_random_chunks(streaming, data, trials=random_trials,
|
|
161
|
+
seed=seed, max_chunk=max_chunk, **opts))
|
|
162
|
+
if decision is not None:
|
|
163
|
+
checks.append(check_decisions(batch, streaming, data, decision=decision))
|
|
164
|
+
if (checkpoint is None) != (restore is None):
|
|
165
|
+
raise ValueError("checkpoint and restore must be provided together")
|
|
166
|
+
if checkpoint is not None:
|
|
167
|
+
checks.extend(check_restart(streaming, data, checkpoint=checkpoint,
|
|
168
|
+
restore=restore, points=restart_points, **opts))
|
|
169
|
+
elif restart_points is not None:
|
|
170
|
+
raise ValueError("restart_points requires checkpoint and restore")
|
|
171
|
+
return AuditReport(tuple(checks))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _positive_int(value, name):
|
|
175
|
+
if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or value < 1:
|
|
176
|
+
raise ValueError(f"{name} must be a positive integer")
|
|
177
|
+
return int(value)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def check_random_chunks(streaming: Factory, data, *, trials=10, seed=0, max_chunk=32,
|
|
181
|
+
rtol=1e-7, atol=1e-10, equal_nan=True) -> tuple[CheckResult, ...]:
|
|
182
|
+
"""Compare random chunk partitions against a fresh single-row replay.
|
|
183
|
+
|
|
184
|
+
The seed makes scenarios reproducible within the same NumPy RNG environment.
|
|
185
|
+
"""
|
|
186
|
+
x = _data(data)
|
|
187
|
+
_tolerances(rtol, atol)
|
|
188
|
+
trials = _positive_int(trials, "trials")
|
|
189
|
+
max_chunk = _positive_int(max_chunk, "max_chunk")
|
|
190
|
+
if isinstance(seed, bool) or not isinstance(seed, (int, np.integer)) or seed < 0:
|
|
191
|
+
raise ValueError("seed must be a nonnegative integer")
|
|
192
|
+
rng = np.random.default_rng(int(seed))
|
|
193
|
+
baseline = _replay(streaming, x, 1)
|
|
194
|
+
results = []
|
|
195
|
+
for trial in range(trials):
|
|
196
|
+
remaining = len(x)
|
|
197
|
+
schedule = []
|
|
198
|
+
while remaining:
|
|
199
|
+
size = int(rng.integers(1, min(max_chunk, remaining)+1))
|
|
200
|
+
schedule.append(size)
|
|
201
|
+
remaining -= size
|
|
202
|
+
actual = _run_schedule(streaming(), x, schedule)
|
|
203
|
+
# Full schedules can be enormous; provide seed/trial to reproduce instead.
|
|
204
|
+
scenario = f"trial={trial},seed={seed},max_chunk={max_chunk}"
|
|
205
|
+
results.append(_compare("random_chunks", scenario, baseline, actual,
|
|
206
|
+
rtol, atol, equal_nan))
|
|
207
|
+
return tuple(results)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def check_restart(streaming: Factory, data, *, checkpoint, restore, points=None,
|
|
211
|
+
rtol=1e-7, atol=1e-10, equal_nan=True) -> tuple[CheckResult, ...]:
|
|
212
|
+
"""Compare uninterrupted single-row replay with checkpoint/restart at each point.
|
|
213
|
+
|
|
214
|
+
checkpoint(update) returns immutable serialized state (bytes); restore(fresh, state)
|
|
215
|
+
mutates a fresh updater in place. Each point is the number of rows already consumed.
|
|
216
|
+
"""
|
|
217
|
+
x = _data(data)
|
|
218
|
+
_tolerances(rtol, atol)
|
|
219
|
+
if len(x) < 2:
|
|
220
|
+
raise ValueError("restart checks require at least two rows")
|
|
221
|
+
if points is None:
|
|
222
|
+
points = sorted({1, len(x)//2, len(x)-1})
|
|
223
|
+
points = tuple(points)
|
|
224
|
+
if not points or any(isinstance(p, bool) or not isinstance(p, (int, np.integer)) or not 1 <= p < len(x) for p in points):
|
|
225
|
+
raise ValueError("restart points must be integers between 1 and len(data)-1")
|
|
226
|
+
baseline = _replay(streaming, x, 1)
|
|
227
|
+
results = []
|
|
228
|
+
for point in points:
|
|
229
|
+
updater = streaming()
|
|
230
|
+
head = _run_schedule(updater, x[:point], (1 for _ in range(point)))
|
|
231
|
+
state = checkpoint(updater)
|
|
232
|
+
if not isinstance(state, bytes):
|
|
233
|
+
raise TypeError("checkpoint must return bytes")
|
|
234
|
+
fresh = streaming()
|
|
235
|
+
restore(fresh, state)
|
|
236
|
+
tail = _run_schedule(fresh, x[point:], (1 for _ in range(len(x)-point)))
|
|
237
|
+
actual = np.concatenate((head, tail), axis=0)
|
|
238
|
+
results.append(_compare("restart", f"after={point}", baseline, actual,
|
|
239
|
+
rtol, atol, equal_nan))
|
|
240
|
+
return tuple(results)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def check_decisions(batch: Transform, streaming: Factory, data, *, decision) -> CheckResult:
|
|
244
|
+
"""Compare exact discrete decisions, even when numerical outputs are close.
|
|
245
|
+
|
|
246
|
+
decision(outputs) must be a deterministic row-wise mapping to bool/int labels.
|
|
247
|
+
"""
|
|
248
|
+
x = _data(data)
|
|
249
|
+
expected = _output(decision(_output(batch(x.copy()), len(x))), len(x))
|
|
250
|
+
actual = _output(decision(_replay(streaming, x, 1)), len(x))
|
|
251
|
+
if expected.dtype.kind not in "biu" or actual.dtype.kind not in "biu":
|
|
252
|
+
raise TypeError("decision must return integer or boolean labels")
|
|
253
|
+
return _compare("decisions", "size=1", expected, actual, 0, 0, False)
|
|
254
|
+
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: streamparity
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Research-to-production consistency testing for numerical and streaming pipelines
|
|
5
|
+
Author: Jaskaran Singh
|
|
6
|
+
Maintainer: Jaskaran Singh
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Project-URL: Homepage, https://github.com/jaskaran04/streamparity
|
|
9
|
+
Project-URL: Repository, https://github.com/jaskaran04/streamparity
|
|
10
|
+
Project-URL: Issues, https://github.com/jaskaran04/streamparity/issues
|
|
11
|
+
Project-URL: Documentation, https://github.com/jaskaran04/streamparity#readme
|
|
12
|
+
Keywords: quantitative-finance,algorithmic-trading,backtesting,lookahead-bias,streaming,numerical-computing,testing,machine-learning,time-series,reproducibility
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
16
|
+
Classifier: Intended Audience :: Science/Research
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Operating System :: OS Independent
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering
|
|
22
|
+
Classifier: Topic :: Software Development :: Testing
|
|
23
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: numpy>=1.24
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
30
|
+
Requires-Dist: build; extra == "dev"
|
|
31
|
+
Requires-Dist: twine; extra == "dev"
|
|
32
|
+
Dynamic: license-file
|
|
33
|
+
|
|
34
|
+
# StreamParity
|
|
35
|
+
|
|
36
|
+
**Test research-to-production consistency in numerical streaming pipelines.**
|
|
37
|
+
|
|
38
|
+
StreamParity is an offline testing toolkit for comparing batch calculations with incremental, stateful implementations. Applications include quantitative trading, numerical risk models, sensor processing and production ML. It is currently an early-stage Python package, not a certified production validation system.
|
|
39
|
+
|
|
40
|
+
## Install from source
|
|
41
|
+
|
|
42
|
+
Requires Python 3.10+ and NumPy. From the repository root:
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
python -m pip install -e ".[dev]"
|
|
46
|
+
python -m pytest -q
|
|
47
|
+
python examples/trading_replay.py
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The name `streamparity` is proposed; public PyPI publication is not yet confirmed.
|
|
51
|
+
|
|
52
|
+
## Quick start
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
import numpy as np
|
|
56
|
+
from streamparity import audit
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def streaming():
|
|
60
|
+
total = 0.0
|
|
61
|
+
|
|
62
|
+
def update(chunk):
|
|
63
|
+
nonlocal total
|
|
64
|
+
out = total + np.cumsum(chunk)
|
|
65
|
+
total = out[-1]
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
return update
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
report = audit(np.cumsum, streaming, [1., -2., 3., -1.],
|
|
72
|
+
random_trials=5, seed=42, max_chunk=3,
|
|
73
|
+
decision=lambda y: y > 0)
|
|
74
|
+
print(report.summary())
|
|
75
|
+
report.assert_passed() # raises AssertionError if a check fails
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Checks
|
|
79
|
+
|
|
80
|
+
| Function | Comparison |
|
|
81
|
+
| --- | --- |
|
|
82
|
+
| `check_batch_stream` | Batch output vs single-row incremental replay |
|
|
83
|
+
| `check_chunks` | Fixed-size partitions vs single-row replay |
|
|
84
|
+
| `check_lookahead` | Full-run historical outputs vs prefix-only executions |
|
|
85
|
+
| `check_random_chunks` | Seeded random partitions vs single-row replay |
|
|
86
|
+
| `check_restart` | Uninterrupted replay vs checkpoint/restart replay |
|
|
87
|
+
| `check_decisions` | Exact discrete decisions from batch vs single-row streaming outputs |
|
|
88
|
+
| `audit` | Combined checks; optional random, restart and decision checks |
|
|
89
|
+
|
|
90
|
+
`AuditReport` provides `.passed`, `.checks`, `.summary()`, `.assert_passed()`, `.to_dict()` and `.to_json()`. Each check reports its scenario, status, count of mismatched rows and zero-based first mismatch. Shape mismatches are reported separately (row mismatch count is zero and index is null). No raw inputs or output values are included in reports. User-selected scenarios are not exhaustive.
|
|
91
|
+
|
|
92
|
+
### Checkpoint recovery
|
|
93
|
+
|
|
94
|
+
A checkpoint callback serializes the updater's state to immutable bytes. A restore callback loads those bytes into a fresh updater in place. Test the same serialization callbacks used by the real application whenever possible.
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from streamparity import check_restart
|
|
98
|
+
|
|
99
|
+
results = check_restart(
|
|
100
|
+
streaming_factory, data,
|
|
101
|
+
checkpoint=lambda updater: updater.save_state(),
|
|
102
|
+
restore=lambda updater, state: updater.load_state(state),
|
|
103
|
+
points=(10, 50), # restart after this many consumed rows
|
|
104
|
+
)
|
|
105
|
+
assert all(r.passed for r in results)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
See `examples/trading_replay.py` for a complete runnable implementation and an intentional recovery failure. This simulates state restoration within a process; it does not kill processes, simulate network failures or verify durability on disk.
|
|
109
|
+
|
|
110
|
+
### Contracts and numerical semantics
|
|
111
|
+
|
|
112
|
+
- `batch(data)` is deterministic and stateless or freshly reset; `streaming()` returns a fresh stateful callable `update(chunk)` for each replay. State is retained across calls to that updater only.
|
|
113
|
+
- Axis 0 is time. Both transforms return one nonempty numerical output row per input row, in identical order. Input and output arrays are copied to isolate ordinary in-place mutations.
|
|
114
|
+
- Real numeric and boolean arrays are supported. Inputs must be nonempty; lookahead, restart and combined audits require at least two rows.
|
|
115
|
+
- Integer/boolean pairs compare exactly; floating or mixed outputs use NumPy `isclose(actual, expected, rtol, atol, equal_nan)`. Mixed integer/floating comparisons may lose precision; return matching discrete dtypes for exact decisions. Matching NaNs are equal by default; set `equal_nan=False` to reject them. Equal infinities compare equal.
|
|
116
|
+
- `decision(outputs)` must be a deterministic row-wise mapping to integer or boolean labels. It is evaluated separately on complete batch and incremental output arrays and compared exactly, not with numerical tolerances. The library cannot verify causality of the user-supplied decision function.
|
|
117
|
+
- Exceptions from user code propagate. Random trials use a nonnegative integer seed and bounded random partitions; a seed and scenario identify a replay within the same NumPy environment.
|
|
118
|
+
|
|
119
|
+
### Limits
|
|
120
|
+
|
|
121
|
+
Passing tests are evidence on the supplied data, scenarios and tolerances, not proof of equivalence, causality or profitable trading. Future-derived features, externally fitted parameters and untested prefixes can evade lookahead checks. Fixed and random partitions preserve input ordering. No asynchronous or late-event replay, timestamp alignment, dataframe metadata, stochastic transform support, distributed execution, or process-crash simulation. The current implementation replays and stores complete outputs; benchmark before large-scale use.
|
|
122
|
+
|
|
123
|
+
## Release preparation
|
|
124
|
+
|
|
125
|
+
See `RELEASING.md`. MIT licence is proposed; review the copyright attribution before distributing. Contributions should include regression tests.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/streamparity/__init__.py
|
|
5
|
+
src/streamparity/core.py
|
|
6
|
+
src/streamparity.egg-info/PKG-INFO
|
|
7
|
+
src/streamparity.egg-info/SOURCES.txt
|
|
8
|
+
src/streamparity.egg-info/dependency_links.txt
|
|
9
|
+
src/streamparity.egg-info/requires.txt
|
|
10
|
+
src/streamparity.egg-info/top_level.txt
|
|
11
|
+
tests/test_core.py
|
|
12
|
+
tests/test_extended.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
streamparity
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pytest
|
|
3
|
+
from streamparity import audit, check_batch_stream, check_chunks, check_lookahead
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def cumulative():
|
|
7
|
+
total = 0.0
|
|
8
|
+
def update(chunk):
|
|
9
|
+
nonlocal total
|
|
10
|
+
out = total + np.cumsum(chunk)
|
|
11
|
+
total = out[-1]
|
|
12
|
+
return out
|
|
13
|
+
return update
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
X = np.arange(1., 11.)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_correct_pipeline():
|
|
20
|
+
report = audit(np.cumsum, cumulative, X)
|
|
21
|
+
assert report.passed
|
|
22
|
+
report.assert_passed()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_missing_state():
|
|
26
|
+
r = check_batch_stream(np.cumsum, lambda: np.cumsum, X)
|
|
27
|
+
assert not r.passed and r.first_mismatch == 1
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_chunk_reset():
|
|
31
|
+
assert not check_chunks(lambda: np.cumsum, X, sizes=(2,))[0].passed
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_lookahead():
|
|
35
|
+
assert not all(r.passed for r in check_lookahead(lambda x: x-x.mean(), X))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_causal():
|
|
39
|
+
assert all(r.passed for r in check_lookahead(np.cumsum, X))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_nan_policy():
|
|
43
|
+
x = np.array([np.nan, 1.])
|
|
44
|
+
assert check_batch_stream(lambda x:x, lambda: lambda x:x, x).passed
|
|
45
|
+
assert not check_batch_stream(lambda x:x, lambda: lambda x:x, x, equal_nan=False).passed
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_shape_mismatch():
|
|
49
|
+
assert not check_batch_stream(lambda x:x[:,None], lambda: lambda x:x, X).passed
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_discrete_exact():
|
|
53
|
+
x = np.array([2**63, 2**63+1], dtype=np.uint64)
|
|
54
|
+
assert not check_batch_stream(lambda x:x, lambda: lambda x:x+1, x).passed
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_input_isolation():
|
|
58
|
+
x = X.copy()
|
|
59
|
+
def mutate(z):
|
|
60
|
+
z[:] = 0
|
|
61
|
+
return z
|
|
62
|
+
assert check_batch_stream(mutate, lambda:mutate, x).passed
|
|
63
|
+
np.testing.assert_array_equal(x, X)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@pytest.mark.parametrize('data', [[], 1, ['a']])
|
|
67
|
+
def test_invalid_input(data):
|
|
68
|
+
with pytest.raises((ValueError, TypeError)):
|
|
69
|
+
check_batch_stream(np.cumsum, cumulative, data)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def test_invalid_settings():
|
|
73
|
+
with pytest.raises(ValueError): check_chunks(cumulative, X, sizes=(0,))
|
|
74
|
+
with pytest.raises(ValueError): check_lookahead(np.cumsum, X, prefixes=(10,))
|
|
75
|
+
with pytest.raises(ValueError): check_batch_stream(np.cumsum, cumulative, X, atol=-1)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_multivariate():
|
|
79
|
+
x = np.arange(12).reshape(6,2)
|
|
80
|
+
assert audit(lambda z:z*2, lambda:lambda z:z*2, x).passed
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_assert_failure():
|
|
84
|
+
report = audit(np.cumsum, lambda: np.cumsum, X)
|
|
85
|
+
with pytest.raises(AssertionError): report.assert_passed()
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import struct
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pytest
|
|
5
|
+
from streamparity import audit, check_random_chunks, check_restart, check_decisions
|
|
6
|
+
|
|
7
|
+
X = np.arange(1., 21.)
|
|
8
|
+
|
|
9
|
+
class Accumulator:
|
|
10
|
+
def __init__(self): self.total = 0.
|
|
11
|
+
def __call__(self, chunk):
|
|
12
|
+
out = self.total + np.cumsum(chunk)
|
|
13
|
+
self.total = out[-1]
|
|
14
|
+
return out
|
|
15
|
+
def checkpoint(self): return struct.pack('!d', self.total)
|
|
16
|
+
def restore(self, state): self.total, = struct.unpack('!d', state)
|
|
17
|
+
|
|
18
|
+
def test_random_partitions_pass():
|
|
19
|
+
assert all(c.passed for c in check_random_chunks(Accumulator, X, seed=17))
|
|
20
|
+
|
|
21
|
+
def test_random_partitions_fail_and_reproduce():
|
|
22
|
+
a = check_random_chunks(lambda: np.cumsum, X, seed=4)
|
|
23
|
+
b = check_random_chunks(lambda: np.cumsum, X, seed=4)
|
|
24
|
+
assert a == b and any(not c.passed for c in a)
|
|
25
|
+
|
|
26
|
+
def test_random_single_row():
|
|
27
|
+
assert all(c.passed for c in check_random_chunks(Accumulator, [1]))
|
|
28
|
+
|
|
29
|
+
@pytest.mark.parametrize('kwargs', [{'trials':0}, {'max_chunk':0}, {'seed':None}, {'seed':-1}])
|
|
30
|
+
def test_invalid_random_settings(kwargs):
|
|
31
|
+
with pytest.raises(ValueError): check_random_chunks(Accumulator, X, **kwargs)
|
|
32
|
+
|
|
33
|
+
def test_restart_success():
|
|
34
|
+
results = check_restart(Accumulator, X, checkpoint=Accumulator.checkpoint,
|
|
35
|
+
restore=Accumulator.restore, points=(1, 10, 19))
|
|
36
|
+
assert all(c.passed for c in results)
|
|
37
|
+
|
|
38
|
+
def test_restart_lost_state():
|
|
39
|
+
results = check_restart(Accumulator, X, checkpoint=Accumulator.checkpoint,
|
|
40
|
+
restore=lambda fresh, state: None, points=(7,))
|
|
41
|
+
assert not results[0].passed and results[0].first_mismatch == 7
|
|
42
|
+
|
|
43
|
+
def test_restart_rejects_nonbytes():
|
|
44
|
+
with pytest.raises(TypeError):
|
|
45
|
+
check_restart(Accumulator, X, checkpoint=lambda u: u.total, restore=Accumulator.restore)
|
|
46
|
+
|
|
47
|
+
@pytest.mark.parametrize('points', [(), (0,), (20,), (True,)])
|
|
48
|
+
def test_bad_restart_points(points):
|
|
49
|
+
with pytest.raises(ValueError):
|
|
50
|
+
check_restart(Accumulator, X, checkpoint=Accumulator.checkpoint,
|
|
51
|
+
restore=Accumulator.restore, points=points)
|
|
52
|
+
|
|
53
|
+
def test_decisions_expose_small_error():
|
|
54
|
+
r = audit(lambda x: x*0+1e-12, lambda: lambda x: x*0-1e-12, X,
|
|
55
|
+
decision=lambda y: y>0)
|
|
56
|
+
assert r.checks[0].passed and not r.checks[-1].passed
|
|
57
|
+
assert r.checks[-1].mismatched_rows == len(X)
|
|
58
|
+
|
|
59
|
+
def test_decisions_exact_pass():
|
|
60
|
+
assert check_decisions(np.cumsum, Accumulator, X, decision=lambda y:y>10).passed
|
|
61
|
+
|
|
62
|
+
def test_decisions_reject_float():
|
|
63
|
+
with pytest.raises(TypeError): check_decisions(np.cumsum, Accumulator, X, decision=lambda y:y)
|
|
64
|
+
|
|
65
|
+
def test_combined_report_and_json():
|
|
66
|
+
report = audit(np.cumsum, Accumulator, X, random_trials=4, decision=lambda x:x>10,
|
|
67
|
+
checkpoint=Accumulator.checkpoint, restore=Accumulator.restore)
|
|
68
|
+
assert report.passed
|
|
69
|
+
assert len(report.checks) == 17
|
|
70
|
+
assert json.loads(report.to_json()) == report.to_dict()
|
|
71
|
+
|
|
72
|
+
def test_invalid_audit_settings():
|
|
73
|
+
with pytest.raises(ValueError): audit(np.cumsum, Accumulator, X, checkpoint=Accumulator.checkpoint)
|
|
74
|
+
with pytest.raises(ValueError): audit(np.cumsum, Accumulator, X, random_trials=-1)
|
|
75
|
+
with pytest.raises(ValueError): audit(np.cumsum, Accumulator, X, restart_points=(1,))
|