Causal-aware execution runtime for production Python systems.
Project description
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.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file cegraph-0.1.0.tar.gz.
File metadata
- Download URL: cegraph-0.1.0.tar.gz
- Upload date:
- Size: 13.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.15
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5a982043b48949a6c964c1ba44958d9da9d9c0121ac4e9d3bc5ff21eee500660
|
|
| MD5 |
92fbcbc76fab6525ae20b37d8e72f885
|
|
| BLAKE2b-256 |
63c008c683d62008fed40a7a80406bfefcabb5198f3ed604c354b65cbeb9dd44
|
File details
Details for the file cegraph-0.1.0-py3-none-any.whl.
File metadata
- Download URL: cegraph-0.1.0-py3-none-any.whl
- Upload date:
- Size: 14.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.15
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
025d71e659a09a0fd99bee371630ef8a7f5e61fd60abd872bf017d6c4afe913b
|
|
| MD5 |
865e30dbdf6171deca143d7d1744b7b8
|
|
| BLAKE2b-256 |
8cfb9c5650bdae776702370ddbc54866d2aee50f55bf7eef62d75f22e75ff62d
|