cegraph
Causal-aware execution runtime for production Python systems.
cegraph tracks causal dependencies between Python functions, records execution traces, runs lightweight counterfactual simulations, and performs adaptive fallback when constraints are violated. Built for MLOps, dynamic decisioning, and root-cause analysis -- no heavy dependencies beyond numpy.
Features
@causal_nodedecorator -- Annotate functions with sensitivity flags and constraint checks, with under 7% overhead vs native calls- CausalGraph -- Directed graph with DFS cycle detection and type-level edge validation. Pure Python, no networkx
- CausalTracer -- Lock-free ring buffer tracer with adaptive sampling. O(1) append, lossy on overflow
- Counterfactual engine -- Deterministic perturbation simulation (
seed=42) with per-node impact scores and confidence - Fallback optimizer -- Evaluate constraints (latency, confidence, critical) and dispatch cache/bypass/error fallback in order
Quick Start
from cegraph import causal_node, CausalGraph, Context, counterfactual, optimize
@causal_node(sensitivity=["price"])
def fetch_price(symbol: str) -> dict:
return {"price": 100.0, "symbol": symbol}
@causal_node(sensitivity=["price"])
def compute_markup(data: dict) -> float:
return data["price"] * 1.1
@causal_node(constraint=lambda x: x > 0)
def apply_strategy(base: float) -> float:
return base * 1.15
graph = CausalGraph()
graph.connect(fetch_price, compute_markup)
graph.connect(compute_markup, apply_strategy)
graph.validate()
with Context(graph=graph, buffer_size=1000) as ctx:
data = fetch_price("AAPL")
base = compute_markup(data)
result = apply_strategy(base)
cf = counterfactual(
base_trace=ctx.tracer.records,
interventions={"fetch_price": {"price": 150.0}},
)
print(f"Impact: {cf.overall_impact:.2f}, Confidence: {cf.confidence:.2f}")
result = optimize(ctx, constraints={"max_latency_ms": 50.0})
print(f"Status: {result.status}")
Installation
pip install cegraph
Requires Python 3.10+ and numpy 1.24+.
Use Cases
MLOps & Model Drift
Production models degrade silently. Isolate the causal node responsible, run counterfactual simulations, and route to fallback automatically.
@causal_node(sensitivity=["feature_distribution"])
def encode_features(raw: dict) -> dict:
return preprocessor.transform(raw)
@causal_node(sensitivity=["feature_distribution"], constraint=lambda x: x > 0.5)
def predict(features: dict) -> float:
return model.predict(features)
@causal_node()
def fallback_predict(features: dict) -> float:
return ensemble_fallback(features)
with Context(buffer_size=5000) as ctx:
score = predict(encode_features(input_data))
When predict violates its confidence constraint, optimize() returns
fallback_cache or fallback_bypass with recommendations.
Dynamic Decisioning
Real-time what-if simulation. "If I raise price 5%, what's the causal impact?"
cf = counterfactual(
base_trace=ctx.tracer.records,
interventions={"pricing_model": {"price_multiplier": 1.05}},
n_perturbations=100,
)
print(f"Estimated impact: {cf.overall_impact:.3f}")
print(f"Sensitivity ranking: {cf.node_impacts}")
Root-Cause Analysis
Replace correlation-timing debugging with explicit causal traces.
summary = ctx.tracer.summary()
for node, stats in summary.items():
print(f"{node}: count={stats['count']}, "
f"mean={stats['mean_latency']:.2f}ms, "
f"p95={stats['p95_latency']:.2f}ms")
API Reference
| API | Description |
|---|---|
@causal_node(sensitivity, constraint, low_sensitivity) |
Decorate a function for causal tracking. constraint raises CausalConstraintViolation on failure. |
NodeMetadata |
Attached to decorated functions as __cegraph_meta__. |
CausalGraph.connect(src, dst) |
Register a causal edge. validate() runs DFS cycle detection + type checking. |
CausalGraph.ancestors(fn) / descendants(fn) |
Traverse upstream/downstream causal dependencies. |
Context(graph, buffer_size, sample_rate) |
Session scope. Binds tracer to all @causal_node calls via threading.local. |
CausalTracer |
Ring buffer (deque(maxlen=N)) with adaptive sampling. Overflow warning once. |
TraceRecord |
__slots__ dataclass per node execution. Fields: node_name, input_hash, output_summary, latency_ms, sensitivity_flags, timestamp, constraint_passed. |
counterfactual(base_trace, interventions, ...) |
Deterministic perturbation engine. Returns CounterfactualResult with per-node ImpactScore. |
optimize(context, objective, constraints) |
Evaluate constraints in order: max_latency_ms -> min_confidence -> critical. Returns OptimizationResult with fallback status. |
Exceptions
| Exception | Raised when |
|---|---|
CegraphError |
Base class for all cegraph errors. |
CausalCycleError |
A cycle is detected in the causal graph. |
CausalTypeError |
Output type of src node mismatches input type of dst node. |
CausalConstraintViolation |
A node's constraint function returns False. |
TracerOverflowWarning |
Ring buffer is full and overwriting old records (warning, not exception). |
Contributing
See CONTRIBUTING.md for development setup, code style, and pull request process. All contributions are welcome.
License
MIT -- see LICENSE for details.
Metadata
Release files for cegraph 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| cegraph-0.1.0.tar.gz | 13.9 kB | Without provenance | Details for cegraph-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| cegraph-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for cegraph-0.1.0-py3-none-any.whl |
Total release size: 28.5 kB
Release files / cegraph-0.1.0.tar.gz
| Download URL | cegraph-0.1.0.tar.gz |
|---|---|
| Size | 13.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5a982043b48949a6c964c1ba44958d9da9d9c0121ac4e9d3bc5ff21eee500660
|
|
BLAKE2b-256 checksum How to use checksums |
63c008c683d62008fed40a7a80406bfefcabb5198f3ed604c354b65cbeb9dd44
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.15
|
Release files / cegraph-0.1.0-py3-none-any.whl
| Download URL | cegraph-0.1.0-py3-none-any.whl |
|---|---|
| Size | 14.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
025d71e659a09a0fd99bee371630ef8a7f5e61fd60abd872bf017d6c4afe913b
|
|
BLAKE2b-256 checksum How to use checksums |
8cfb9c5650bdae776702370ddbc54866d2aee50f55bf7eef62d75f22e75ff62d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.11.15
|
Security for cegraph 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.