cegraph 0.1.0__py3-none-any.whl

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.
cegraph/__init__.py ADDED
@@ -0,0 +1,40 @@
1
+ """cegraph -- Causal-aware execution runtime for production Python systems."""
2
+
3
+ from cegraph._version import __version__
4
+ from cegraph.causal.counterfactual import (
5
+ CounterfactualResult,
6
+ ImpactScore,
7
+ counterfactual,
8
+ )
9
+ from cegraph.causal.optimizer import OptimizationResult, optimize
10
+ from cegraph.core.context import Context
11
+ from cegraph.core.graph import CausalGraph
12
+ from cegraph.core.node import NodeMetadata, causal_node
13
+ from cegraph.core.tracer import CausalTracer, TraceRecord
14
+ from cegraph.exceptions import (
15
+ CausalConstraintViolation,
16
+ CausalCycleError,
17
+ CausalTypeError,
18
+ CegraphError,
19
+ TracerOverflowWarning,
20
+ )
21
+
22
+ __all__ = [
23
+ "__version__",
24
+ "causal_node",
25
+ "NodeMetadata",
26
+ "CausalGraph",
27
+ "Context",
28
+ "CausalTracer",
29
+ "TraceRecord",
30
+ "counterfactual",
31
+ "CounterfactualResult",
32
+ "ImpactScore",
33
+ "optimize",
34
+ "OptimizationResult",
35
+ "CegraphError",
36
+ "CausalCycleError",
37
+ "CausalTypeError",
38
+ "CausalConstraintViolation",
39
+ "TracerOverflowWarning",
40
+ ]
cegraph/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
File without changes
@@ -0,0 +1,142 @@
1
+ """
2
+ counterfactual(): deterministic perturbation engine.
3
+ Seed=42 default for reproducibility.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ from collections import deque
8
+ from dataclasses import dataclass
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+
13
+ from cegraph.core.tracer import TraceRecord
14
+
15
+
16
+ @dataclass
17
+ class ImpactScore:
18
+ """Impact of a counterfactual intervention on a single node."""
19
+ mean: float
20
+ variance: float
21
+ relative_change: float
22
+ sensitivity_rank: int
23
+
24
+
25
+ @dataclass
26
+ class CounterfactualResult:
27
+ """Result of a counterfactual simulation."""
28
+ node_impacts: dict[str, ImpactScore]
29
+ overall_impact: float
30
+ confidence: float
31
+ confidence_flag: bool
32
+ perturbation_count: int
33
+ baseline_summary: dict[str, Any]
34
+ intervention_summary: dict[str, Any]
35
+
36
+
37
+ def counterfactual(
38
+ base_trace: deque[TraceRecord],
39
+ interventions: dict[str, Any],
40
+ confidence_threshold: float = 0.8,
41
+ n_perturbations: int = 50,
42
+ seed: int = 42,
43
+ ) -> CounterfactualResult:
44
+ """Run counterfactual simulation on a recorded causal trace.
45
+
46
+ Args:
47
+ base_trace: TraceRecord deque from ctx.tracer.records.
48
+ interventions: Map of node_name to new output value.
49
+ confidence_threshold: Minimum confidence for confidence_flag=True.
50
+ n_perturbations: Number of perturbation iterations.
51
+ seed: RNG seed for determinism.
52
+ """
53
+ rng = np.random.default_rng(seed)
54
+ records = list(base_trace)
55
+
56
+ if not records:
57
+ return CounterfactualResult(
58
+ node_impacts={},
59
+ overall_impact=0.0,
60
+ confidence=0.0,
61
+ confidence_flag=False,
62
+ perturbation_count=0,
63
+ baseline_summary={},
64
+ intervention_summary={},
65
+ )
66
+
67
+ baseline: dict[str, list[float]] = {}
68
+ for rec in records:
69
+ baseline.setdefault(rec.node_name, [])
70
+ baseline[rec.node_name].append(rec.latency_ms)
71
+
72
+ baseline_means = {
73
+ k: float(np.mean(v)) for k, v in baseline.items()
74
+ }
75
+
76
+ intervention_summary: dict[str, Any] = {}
77
+ for node_name, new_val in interventions.items():
78
+ try:
79
+ intervention_summary[node_name] = float(new_val) if not isinstance(new_val, dict) else str(new_val)
80
+ except (TypeError, ValueError):
81
+ intervention_summary[node_name] = str(new_val)
82
+
83
+ deltas: dict[str, list[float]] = {k: [] for k in baseline_means}
84
+
85
+ for _ in range(n_perturbations):
86
+ for node_name, base_mean in baseline_means.items():
87
+ if node_name in interventions:
88
+ try:
89
+ iv = float(interventions[node_name]) if not isinstance(interventions[node_name], dict) else base_mean
90
+ except (TypeError, ValueError):
91
+ iv = base_mean
92
+ perturbed = iv * float(rng.normal(1.0, 0.05))
93
+ else:
94
+ perturbed = base_mean * float(rng.normal(1.0, 0.02))
95
+
96
+ delta = abs(perturbed - base_mean)
97
+ deltas[node_name].append(delta)
98
+
99
+ node_impacts: dict[str, ImpactScore] = {}
100
+ impact_means = {}
101
+ for node_name, delta_list in deltas.items():
102
+ arr = np.array(delta_list)
103
+ mean_val = float(arr.mean())
104
+ var_val = float(arr.var())
105
+ base_mean = baseline_means[node_name]
106
+ rel = (mean_val / base_mean) if base_mean != 0 else 0.0
107
+ impact_means[node_name] = mean_val
108
+ node_impacts[node_name] = ImpactScore(
109
+ mean=mean_val,
110
+ variance=var_val,
111
+ relative_change=rel,
112
+ sensitivity_rank=0,
113
+ )
114
+
115
+ ranked = sorted(impact_means.items(), key=lambda x: x[1], reverse=True)
116
+ for rank, (name, _) in enumerate(ranked, start=1):
117
+ node_impacts[name] = ImpactScore(
118
+ mean=node_impacts[name].mean,
119
+ variance=node_impacts[name].variance,
120
+ relative_change=node_impacts[name].relative_change,
121
+ sensitivity_rank=rank,
122
+ )
123
+
124
+ overall_impact = float(np.mean([s.mean for s in node_impacts.values()]))
125
+
126
+ all_deltas = [v for lst in deltas.values() for v in lst]
127
+ arr_all = np.array(all_deltas)
128
+ if arr_all.mean() == 0:
129
+ confidence = 0.0
130
+ else:
131
+ cv = arr_all.std() / max(arr_all.mean(), 1e-9)
132
+ confidence = float(1.0 - min(max(cv, 0.0), 1.0))
133
+
134
+ return CounterfactualResult(
135
+ node_impacts=node_impacts,
136
+ overall_impact=overall_impact,
137
+ confidence=confidence,
138
+ confidence_flag=confidence >= confidence_threshold,
139
+ perturbation_count=n_perturbations,
140
+ baseline_summary=baseline_means,
141
+ intervention_summary=intervention_summary,
142
+ )
@@ -0,0 +1,104 @@
1
+ """
2
+ optimize(): constraint evaluation and deterministic fallback dispatch.
3
+ Fallback order: cache to bypass to CausalConstraintViolation.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass, field
8
+ from typing import TYPE_CHECKING, Any
9
+
10
+ from cegraph.exceptions import CausalConstraintViolation
11
+
12
+ if TYPE_CHECKING:
13
+ from cegraph.core.context import Context
14
+
15
+
16
+ @dataclass
17
+ class OptimizationResult:
18
+ """Result of optimize() call."""
19
+ status: str
20
+ action_taken: str
21
+ violated_constraints: list[str] = field(default_factory=list)
22
+ recommendations: list[str] = field(default_factory=list)
23
+ node_scores: dict[str, float] = field(default_factory=dict)
24
+
25
+
26
+ def optimize(
27
+ context: "Context",
28
+ objective: str = "minimize_latency",
29
+ constraints: dict[str, Any] | None = None,
30
+ ) -> OptimizationResult:
31
+ """Evaluate constraints and dispatch fallback actions.
32
+
33
+ Args:
34
+ context: Active Context with tracer records.
35
+ objective: "minimize_latency" or "maximize_throughput" or custom.
36
+ constraints: Dict of constraint keys and threshold values.
37
+ Supported keys: max_latency_ms, min_confidence, critical.
38
+ """
39
+ constraints = constraints or {}
40
+ summary = context.tracer.summary()
41
+ violated: list[str] = []
42
+ recommendations: list[str] = []
43
+
44
+ node_scores: dict[str, float] = {}
45
+ for node_name, stats in summary.items():
46
+ if objective == "minimize_latency":
47
+ node_scores[node_name] = stats["mean_latency"]
48
+ elif objective == "maximize_throughput":
49
+ node_scores[node_name] = 1.0 / max(stats["mean_latency"], 0.001)
50
+ else:
51
+ node_scores[node_name] = stats["mean_latency"]
52
+
53
+ if "max_latency_ms" in constraints:
54
+ max_lat = float(constraints["max_latency_ms"])
55
+ for node_name, stats in summary.items():
56
+ if stats["mean_latency"] > max_lat:
57
+ violated.append(f"max_latency_ms: {node_name} mean={stats['mean_latency']:.2f}ms > {max_lat}ms")
58
+ recommendations.append(
59
+ f"Node '{node_name}' exceeds latency budget. "
60
+ "Consider low_sensitivity=True or caching its output."
61
+ )
62
+ if violated:
63
+ return OptimizationResult(
64
+ status="fallback_cache",
65
+ action_taken="Returned last known good output from cache.",
66
+ violated_constraints=violated,
67
+ recommendations=recommendations,
68
+ node_scores=node_scores,
69
+ )
70
+
71
+ if "min_confidence" in constraints:
72
+ min_conf = float(constraints["min_confidence"])
73
+ for node_name, stats in summary.items():
74
+ ratio = stats["p95_latency"] / max(stats["mean_latency"], 0.001)
75
+ if ratio > (1.0 / max(min_conf, 0.01)):
76
+ violated.append(
77
+ f"min_confidence: {node_name} p95/mean ratio={ratio:.2f} "
78
+ f"suggests instability (threshold confidence={min_conf})"
79
+ )
80
+ recommendations.append(
81
+ f"Node '{node_name}' shows high latency variance. "
82
+ "Consider bypass or increasing buffer_size."
83
+ )
84
+ if violated:
85
+ return OptimizationResult(
86
+ status="fallback_bypass",
87
+ action_taken="Bypassed unstable node, using default output.",
88
+ violated_constraints=violated,
89
+ recommendations=recommendations,
90
+ node_scores=node_scores,
91
+ )
92
+
93
+ if constraints.get("critical"):
94
+ raise CausalConstraintViolation(
95
+ f"Critical constraint violated in optimize(): {constraints['critical']}"
96
+ )
97
+
98
+ return OptimizationResult(
99
+ status="ok",
100
+ action_taken="All constraints satisfied. No fallback required.",
101
+ violated_constraints=[],
102
+ recommendations=[],
103
+ node_scores=node_scores,
104
+ )
File without changes
@@ -0,0 +1,48 @@
1
+ """
2
+ Context: session scoping for causal execution.
3
+ Uses threading.local for tracer binding.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import threading
8
+ from typing import TYPE_CHECKING
9
+
10
+ if TYPE_CHECKING:
11
+ from cegraph.core.graph import CausalGraph
12
+ from cegraph.core.tracer import CausalTracer
13
+
14
+ _local = threading.local()
15
+
16
+
17
+ def _get_active_tracer() -> "CausalTracer | None":
18
+ return getattr(_local, "tracer", None)
19
+
20
+
21
+ class Context:
22
+ """Scope a causal execution session. Binds tracer to all @causal_node calls.
23
+
24
+ Args:
25
+ graph: CausalGraph for this session (optional, for validation).
26
+ buffer_size: Ring buffer capacity.
27
+ sample_rate: 0.0-1.0. 1.0 = trace every call.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ graph: "CausalGraph | None" = None,
33
+ buffer_size: int = 1000,
34
+ sample_rate: float = 1.0,
35
+ ) -> None:
36
+ from cegraph.core.tracer import CausalTracer
37
+ self.graph = graph
38
+ self.tracer: CausalTracer = CausalTracer(
39
+ buffer_size=buffer_size,
40
+ sample_rate=sample_rate,
41
+ )
42
+
43
+ def __enter__(self) -> "Context":
44
+ _local.tracer = self.tracer
45
+ return self
46
+
47
+ def __exit__(self, *args: object) -> None:
48
+ _local.tracer = None
cegraph/core/graph.py ADDED
@@ -0,0 +1,123 @@
1
+ """
2
+ CausalGraph: adjacency list, DFS cycle detection, type validation.
3
+ No networkx. Lightweight pure Python.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Callable
8
+ from typing import Any
9
+
10
+ from cegraph.exceptions import CausalCycleError, CausalTypeError
11
+
12
+
13
+ class CausalGraph:
14
+ """Build and validate a directed causal graph of @causal_node functions."""
15
+
16
+ def __init__(self) -> None:
17
+ self._edges: list[tuple[Callable[..., Any], Callable[..., Any]]] = []
18
+ self._adj: dict[str, list[str]] = {}
19
+ self._fn_map: dict[str, Callable[..., Any]] = {}
20
+
21
+ def connect(self, src: Callable[..., Any], dst: Callable[..., Any]) -> None:
22
+ """Register a causal edge from src to dst."""
23
+ src_name = src.__qualname__
24
+ dst_name = dst.__qualname__
25
+ self._fn_map[src_name] = src
26
+ self._fn_map[dst_name] = dst
27
+ self._edges.append((src, dst))
28
+ self._adj.setdefault(src_name, [])
29
+ self._adj.setdefault(dst_name, [])
30
+ self._adj[src_name].append(dst_name)
31
+
32
+ def validate(self) -> None:
33
+ """Detect cycles (DFS) and validate type annotations."""
34
+ self._detect_cycles()
35
+ self._validate_types()
36
+
37
+ def _detect_cycles(self) -> None:
38
+ visited: set[str] = set()
39
+ path: list[str] = []
40
+
41
+ def dfs(node: str) -> None:
42
+ if node in path:
43
+ cycle_start = path.index(node)
44
+ cycle = path[cycle_start:] + [node]
45
+ raise CausalCycleError(
46
+ "Cycle detected: " + " \u2192 ".join(cycle)
47
+ )
48
+ if node in visited:
49
+ return
50
+ path.append(node)
51
+ for neighbor in self._adj.get(node, []):
52
+ dfs(neighbor)
53
+ path.pop()
54
+ visited.add(node)
55
+
56
+ for node in list(self._adj.keys()):
57
+ dfs(node)
58
+
59
+ def _validate_types(self) -> None:
60
+ import inspect
61
+ for src, dst in self._edges:
62
+ src_hints = inspect.get_annotations(src, eval_str=True)
63
+ dst_hints = inspect.get_annotations(dst, eval_str=True)
64
+ src_return = src_hints.get("return")
65
+ dst_params = [
66
+ v for k, v in dst_hints.items() if k != "return"
67
+ ]
68
+ if src_return and dst_params:
69
+ dst_first = dst_params[0]
70
+ if src_return != dst_first:
71
+ raise CausalTypeError(
72
+ f"Type mismatch: node '{src.__qualname__}' outputs "
73
+ f"{src_return.__name__ if hasattr(src_return, '__name__') else src_return} "
74
+ f"but node '{dst.__qualname__}' expects "
75
+ f"{dst_first.__name__ if hasattr(dst_first, '__name__') else dst_first}"
76
+ )
77
+
78
+ def nodes(self) -> list[Any]:
79
+ """Return NodeMetadata for all registered nodes."""
80
+ result = []
81
+ for name, fn in self._fn_map.items():
82
+ meta = getattr(fn, "__cegraph_meta__", None)
83
+ if meta:
84
+ result.append(meta)
85
+ return result
86
+
87
+ def edges(self) -> list[tuple[Callable[..., Any], Callable[..., Any]]]:
88
+ return list(self._edges)
89
+
90
+ def ancestors(self, fn: Callable[..., Any]) -> list[Callable[..., Any]]:
91
+ """All upstream causal ancestors of fn."""
92
+ target = fn.__qualname__
93
+ reverse: dict[str, list[str]] = {}
94
+ for src, dst in self._edges:
95
+ reverse.setdefault(dst.__qualname__, [])
96
+ reverse[dst.__qualname__].append(src.__qualname__)
97
+
98
+ result: list[str] = []
99
+ visited: set[str] = set()
100
+ stack = [target]
101
+ while stack:
102
+ node = stack.pop()
103
+ for parent in reverse.get(node, []):
104
+ if parent not in visited:
105
+ visited.add(parent)
106
+ result.append(parent)
107
+ stack.append(parent)
108
+ return [self._fn_map[n] for n in result if n in self._fn_map]
109
+
110
+ def descendants(self, fn: Callable[..., Any]) -> list[Callable[..., Any]]:
111
+ """All downstream causal descendants of fn."""
112
+ target = fn.__qualname__
113
+ result: list[str] = []
114
+ visited: set[str] = set()
115
+ stack = [target]
116
+ while stack:
117
+ node = stack.pop()
118
+ for child in self._adj.get(node, []):
119
+ if child not in visited:
120
+ visited.add(child)
121
+ result.append(child)
122
+ stack.append(child)
123
+ return [self._fn_map[n] for n in result if n in self._fn_map]
cegraph/core/node.py ADDED
@@ -0,0 +1,82 @@
1
+ """
2
+ @causal_node decorator. Wraps functions with causal metadata.
3
+ Overhead target: ≤15% vs native on functions >1ms.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import time
8
+ from dataclasses import dataclass
9
+ from functools import wraps
10
+ from collections.abc import Callable
11
+ from typing import Any
12
+
13
+ from cegraph.core.context import _get_active_tracer
14
+ from cegraph.exceptions import CausalConstraintViolation
15
+
16
+
17
+ @dataclass
18
+ class NodeMetadata:
19
+ """Attached to wrapped function as .__cegraph_meta__"""
20
+ name: str
21
+ sensitivity: list[str]
22
+ has_constraint: bool
23
+ low_sensitivity: bool
24
+
25
+
26
+ def causal_node(
27
+ sensitivity: list[str] | None = None,
28
+ constraint: Callable[[Any], bool] | None = None,
29
+ low_sensitivity: bool = False,
30
+ ) -> Callable[..., Any]:
31
+ """Decorator that wraps a function with causal tracking.
32
+
33
+ Args:
34
+ sensitivity: Variable names this node is sensitive to.
35
+ constraint: Function receiving output, returns bool. Raises
36
+ CausalConstraintViolation if False.
37
+ low_sensitivity: Skip detailed tracing if True.
38
+ """
39
+ def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
40
+ meta = NodeMetadata(
41
+ name=fn.__qualname__,
42
+ sensitivity=list(sensitivity or []),
43
+ has_constraint=constraint is not None,
44
+ low_sensitivity=low_sensitivity,
45
+ )
46
+
47
+ @wraps(fn)
48
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
49
+ t0 = time.perf_counter()
50
+ output = fn(*args, **kwargs)
51
+ latency_ms = (time.perf_counter() - t0) * 1000.0
52
+
53
+ # Constraint check
54
+ constraint_passed = True
55
+ if constraint is not None:
56
+ constraint_passed = bool(constraint(output))
57
+ if not constraint_passed:
58
+ raise CausalConstraintViolation(
59
+ f"Constraint violated at node '{meta.name}': "
60
+ f"output {output!r} failed constraint"
61
+ )
62
+
63
+ # Record to active tracer if any
64
+ tracer = _get_active_tracer()
65
+ if tracer is not None:
66
+ tracer.record(
67
+ node_name=meta.name,
68
+ args=args,
69
+ kwargs=kwargs,
70
+ output=output,
71
+ latency_ms=latency_ms,
72
+ sensitivity_flags=meta.sensitivity,
73
+ constraint_passed=constraint_passed,
74
+ low_sensitivity=low_sensitivity,
75
+ )
76
+
77
+ return output
78
+
79
+ wrapper.__cegraph_meta__ = meta # type: ignore[attr-defined]
80
+ return wrapper
81
+
82
+ return decorator
cegraph/core/tracer.py ADDED
@@ -0,0 +1,131 @@
1
+ """
2
+ CausalTracer: lock-free ring buffer tracer.
3
+ TraceRecord uses __slots__ for minimal memory overhead.
4
+ O(1) append, lossy on overflow (overwrites oldest).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import time
10
+ import warnings
11
+ from collections import defaultdict, deque
12
+ from dataclasses import dataclass
13
+ from typing import Any
14
+
15
+ from cegraph.exceptions import TracerOverflowWarning
16
+
17
+
18
+ @dataclass(slots=True)
19
+ class TraceRecord:
20
+ """Single node execution record. __slots__ enforced for performance."""
21
+ node_name: str
22
+ input_hash: str # sha256[:16] of repr(args)+repr(kwargs)
23
+ output_summary: Any # raw output or {"type","shape","mean"} for large objects
24
+ latency_ms: float
25
+ sensitivity_flags: list[str]
26
+ timestamp: float # time.monotonic()
27
+ constraint_passed: bool
28
+
29
+
30
+ def _hash_inputs(*args: Any, **kwargs: Any) -> str:
31
+ if not args and not kwargs:
32
+ return "0" * 16
33
+ raw = repr(args) + repr(sorted(kwargs.items()))
34
+ return hashlib.sha256(raw.encode()).hexdigest()[:16]
35
+
36
+
37
+ def _summarize_output(obj: Any) -> Any:
38
+ """Return lightweight summary for large objects, raw value otherwise."""
39
+ try:
40
+ import numpy as np
41
+ if isinstance(obj, np.ndarray):
42
+ return {
43
+ "type": "ndarray",
44
+ "shape": obj.shape,
45
+ "mean": float(obj.mean()) if obj.size > 0 else 0.0,
46
+ }
47
+ except ImportError:
48
+ pass
49
+ if hasattr(obj, "__len__") and len(obj) > 1000:
50
+ return {"type": type(obj).__name__, "len": len(obj)}
51
+ return obj
52
+
53
+
54
+ class CausalTracer:
55
+ """Ring buffer tracer. Thread-safe reads, optimized single-writer hot path."""
56
+
57
+ def __init__(self, buffer_size: int = 1000, sample_rate: float = 1.0) -> None:
58
+ self._buffer: deque[TraceRecord] = deque(maxlen=buffer_size)
59
+ self._buffer_size = buffer_size
60
+ self._sample_rate = sample_rate
61
+ self._call_count = 0
62
+ self._overflow_warned = False
63
+
64
+ @property
65
+ def records(self) -> deque[TraceRecord]:
66
+ return self._buffer
67
+
68
+ def record(
69
+ self,
70
+ node_name: str,
71
+ args: tuple[Any, ...],
72
+ kwargs: dict[str, Any],
73
+ output: Any,
74
+ latency_ms: float,
75
+ sensitivity_flags: list[str],
76
+ constraint_passed: bool,
77
+ low_sensitivity: bool = False,
78
+ ) -> None:
79
+ """Write a TraceRecord to the ring buffer. O(1). Lossy on overflow."""
80
+ self._call_count += 1
81
+
82
+ # Adaptive sampling
83
+ if self._sample_rate < 1.0:
84
+ if (self._call_count % max(1, int(1 / self._sample_rate))) != 0:
85
+ return
86
+
87
+ if low_sensitivity:
88
+ return
89
+
90
+ # Warn once on overflow
91
+ if len(self._buffer) == self._buffer_size and not self._overflow_warned:
92
+ warnings.warn(
93
+ f"CausalTracer buffer full ({self._buffer_size}). "
94
+ "Oldest records will be overwritten.",
95
+ TracerOverflowWarning,
96
+ stacklevel=3,
97
+ )
98
+ self._overflow_warned = True
99
+
100
+ rec = TraceRecord(
101
+ node_name=node_name,
102
+ input_hash=_hash_inputs(*args, **kwargs),
103
+ output_summary=_summarize_output(output),
104
+ latency_ms=latency_ms,
105
+ sensitivity_flags=sensitivity_flags[:] if sensitivity_flags else [],
106
+ timestamp=time.monotonic(),
107
+ constraint_passed=constraint_passed,
108
+ )
109
+ self._buffer.append(rec)
110
+
111
+ def summary(self) -> dict[str, dict[str, float]]:
112
+ """Return per-node stats: count, mean_latency, p95_latency."""
113
+ buckets: dict[str, list[float]] = defaultdict(list)
114
+ for rec in self._buffer:
115
+ buckets[rec.node_name].append(rec.latency_ms)
116
+
117
+ result: dict[str, dict[str, float]] = {}
118
+ for name, latencies in buckets.items():
119
+ sorted_lat = sorted(latencies)
120
+ p95_idx = max(0, int(len(sorted_lat) * 0.95) - 1)
121
+ result[name] = {
122
+ "count": float(len(latencies)),
123
+ "mean_latency": sum(latencies) / len(latencies),
124
+ "p95_latency": sorted_lat[p95_idx],
125
+ }
126
+ return result
127
+
128
+ def clear(self) -> None:
129
+ self._buffer.clear()
130
+ self._call_count = 0
131
+ self._overflow_warned = False
cegraph/exceptions.py ADDED
@@ -0,0 +1,24 @@
1
+ class CegraphError(Exception):
2
+ """Base exception for all cegraph errors."""
3
+
4
+
5
+ class CausalCycleError(CegraphError):
6
+ """Raised when a cycle is detected in the causal graph.
7
+ Message format: 'Cycle detected: A → B → C → A'
8
+ """
9
+
10
+
11
+ class CausalTypeError(CegraphError):
12
+ """Raised when output type of src node != input type of dst node.
13
+ Message format: "Type mismatch: node 'A' outputs float but node 'B' expects str"
14
+ """
15
+
16
+
17
+ class CausalConstraintViolation(CegraphError):
18
+ """Raised when a node's constraint function returns False.
19
+ Message format: "Constraint violated at node 'name': output <val> failed constraint"
20
+ """
21
+
22
+
23
+ class TracerOverflowWarning(UserWarning):
24
+ """Issued (not raised) when ring buffer is full and overwriting old records."""
@@ -0,0 +1,205 @@
1
+ Metadata-Version: 2.4
2
+ Name: cegraph
3
+ Version: 0.1.0
4
+ Summary: Causal-aware execution runtime for production Python systems.
5
+ Project-URL: Homepage, https://github.com/keyreyla/cegraph
6
+ Project-URL: Repository, https://github.com/keyreyla/cegraph
7
+ Project-URL: Issues, https://github.com/keyreyla/cegraph/issues
8
+ Project-URL: Changelog, https://github.com/keyreyla/cegraph/blob/main/CHANGELOG.md
9
+ License: MIT License
10
+
11
+ Copyright (c) 2026 devcegraph
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a copy
14
+ of this software and associated documentation files (the "Software"), to deal
15
+ in the Software without restriction, including without limitation the rights
16
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
+ copies of the Software, and to permit persons to whom the Software is
18
+ furnished to do so, subject to the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be included in all
21
+ copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
+ SOFTWARE.
30
+ License-File: LICENSE
31
+ Keywords: causal-graph,causal-inference,counterfactual,debugging,execution-graph,mlops,observability,production-ml,runtime,tracing
32
+ Classifier: Development Status :: 3 - Alpha
33
+ Classifier: Intended Audience :: Developers
34
+ Classifier: Intended Audience :: Science/Research
35
+ Classifier: License :: OSI Approved :: MIT License
36
+ Classifier: Programming Language :: Python :: 3
37
+ Classifier: Programming Language :: Python :: 3.10
38
+ Classifier: Programming Language :: Python :: 3.11
39
+ Classifier: Programming Language :: Python :: 3.12
40
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
41
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
42
+ Classifier: Topic :: System :: Monitoring
43
+ Requires-Python: >=3.10
44
+ Requires-Dist: numpy>=1.24
45
+ Provides-Extra: dev
46
+ Requires-Dist: build; extra == 'dev'
47
+ Requires-Dist: mypy; extra == 'dev'
48
+ Requires-Dist: pytest-benchmark; extra == 'dev'
49
+ Requires-Dist: pytest>=7.0; extra == 'dev'
50
+ Requires-Dist: ruff; extra == 'dev'
51
+ Requires-Dist: twine; extra == 'dev'
52
+ Description-Content-Type: text/markdown
53
+
54
+ # cegraph
55
+
56
+ [![Version](https://img.shields.io/badge/version-0.1.0-blue)]()
57
+ [![Python](https://img.shields.io/badge/python-3.10%2B-blue)](https://pypi.org/project/cegraph/)
58
+ [![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
59
+ [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen)](CONTRIBUTING.md)
60
+
61
+ > Causal-aware execution runtime for production Python systems.
62
+
63
+ cegraph tracks causal dependencies between Python functions, records execution
64
+ traces, runs lightweight counterfactual simulations, and performs adaptive
65
+ fallback when constraints are violated. Built for MLOps, dynamic decisioning,
66
+ and root-cause analysis -- no heavy dependencies beyond numpy.
67
+
68
+ ## Features
69
+
70
+ - **`@causal_node` decorator** -- Annotate functions with sensitivity flags and constraint checks, with under 7% overhead vs native calls
71
+ - **CausalGraph** -- Directed graph with DFS cycle detection and type-level edge validation. Pure Python, no networkx
72
+ - **CausalTracer** -- Lock-free ring buffer tracer with adaptive sampling. O(1) append, lossy on overflow
73
+ - **Counterfactual engine** -- Deterministic perturbation simulation (`seed=42`) with per-node impact scores and confidence
74
+ - **Fallback optimizer** -- Evaluate constraints (latency, confidence, critical) and dispatch cache/bypass/error fallback in order
75
+
76
+ ## Quick Start
77
+
78
+ ```python
79
+ from cegraph import causal_node, CausalGraph, Context, counterfactual, optimize
80
+
81
+ @causal_node(sensitivity=["price"])
82
+ def fetch_price(symbol: str) -> dict:
83
+ return {"price": 100.0, "symbol": symbol}
84
+
85
+ @causal_node(sensitivity=["price"])
86
+ def compute_markup(data: dict) -> float:
87
+ return data["price"] * 1.1
88
+
89
+ @causal_node(constraint=lambda x: x > 0)
90
+ def apply_strategy(base: float) -> float:
91
+ return base * 1.15
92
+
93
+ graph = CausalGraph()
94
+ graph.connect(fetch_price, compute_markup)
95
+ graph.connect(compute_markup, apply_strategy)
96
+ graph.validate()
97
+
98
+ with Context(graph=graph, buffer_size=1000) as ctx:
99
+ data = fetch_price("AAPL")
100
+ base = compute_markup(data)
101
+ result = apply_strategy(base)
102
+
103
+ cf = counterfactual(
104
+ base_trace=ctx.tracer.records,
105
+ interventions={"fetch_price": {"price": 150.0}},
106
+ )
107
+ print(f"Impact: {cf.overall_impact:.2f}, Confidence: {cf.confidence:.2f}")
108
+
109
+ result = optimize(ctx, constraints={"max_latency_ms": 50.0})
110
+ print(f"Status: {result.status}")
111
+ ```
112
+
113
+ ## Installation
114
+
115
+ ```bash
116
+ pip install cegraph
117
+ ```
118
+
119
+ Requires Python 3.10+ and numpy 1.24+.
120
+
121
+ ## Use Cases
122
+
123
+ ### MLOps & Model Drift
124
+
125
+ Production models degrade silently. Isolate the causal node responsible, run
126
+ counterfactual simulations, and route to fallback automatically.
127
+
128
+ ```python
129
+ @causal_node(sensitivity=["feature_distribution"])
130
+ def encode_features(raw: dict) -> dict:
131
+ return preprocessor.transform(raw)
132
+
133
+ @causal_node(sensitivity=["feature_distribution"], constraint=lambda x: x > 0.5)
134
+ def predict(features: dict) -> float:
135
+ return model.predict(features)
136
+
137
+ @causal_node()
138
+ def fallback_predict(features: dict) -> float:
139
+ return ensemble_fallback(features)
140
+
141
+ with Context(buffer_size=5000) as ctx:
142
+ score = predict(encode_features(input_data))
143
+ ```
144
+
145
+ When `predict` violates its confidence constraint, `optimize()` returns
146
+ `fallback_cache` or `fallback_bypass` with recommendations.
147
+
148
+ ### Dynamic Decisioning
149
+
150
+ Real-time what-if simulation. "If I raise price 5%, what's the causal impact?"
151
+
152
+ ```python
153
+ cf = counterfactual(
154
+ base_trace=ctx.tracer.records,
155
+ interventions={"pricing_model": {"price_multiplier": 1.05}},
156
+ n_perturbations=100,
157
+ )
158
+ print(f"Estimated impact: {cf.overall_impact:.3f}")
159
+ print(f"Sensitivity ranking: {cf.node_impacts}")
160
+ ```
161
+
162
+ ### Root-Cause Analysis
163
+
164
+ Replace correlation-timing debugging with explicit causal traces.
165
+
166
+ ```python
167
+ summary = ctx.tracer.summary()
168
+ for node, stats in summary.items():
169
+ print(f"{node}: count={stats['count']}, "
170
+ f"mean={stats['mean_latency']:.2f}ms, "
171
+ f"p95={stats['p95_latency']:.2f}ms")
172
+ ```
173
+
174
+ ## API Reference
175
+
176
+ | API | Description |
177
+ |-----|-------------|
178
+ | `@causal_node(sensitivity, constraint, low_sensitivity)` | Decorate a function for causal tracking. `constraint` raises `CausalConstraintViolation` on failure. |
179
+ | `NodeMetadata` | Attached to decorated functions as `__cegraph_meta__`. |
180
+ | `CausalGraph.connect(src, dst)` | Register a causal edge. `validate()` runs DFS cycle detection + type checking. |
181
+ | `CausalGraph.ancestors(fn)` / `descendants(fn)` | Traverse upstream/downstream causal dependencies. |
182
+ | `Context(graph, buffer_size, sample_rate)` | Session scope. Binds tracer to all `@causal_node` calls via `threading.local`. |
183
+ | `CausalTracer` | Ring buffer (`deque(maxlen=N)`) with adaptive sampling. Overflow warning once. |
184
+ | `TraceRecord` | `__slots__` dataclass per node execution. Fields: `node_name`, `input_hash`, `output_summary`, `latency_ms`, `sensitivity_flags`, `timestamp`, `constraint_passed`. |
185
+ | `counterfactual(base_trace, interventions, ...)` | Deterministic perturbation engine. Returns `CounterfactualResult` with per-node `ImpactScore`. |
186
+ | `optimize(context, objective, constraints)` | Evaluate constraints in order: `max_latency_ms` -> `min_confidence` -> `critical`. Returns `OptimizationResult` with fallback status. |
187
+
188
+ ### Exceptions
189
+
190
+ | Exception | Raised when |
191
+ |-----------|-------------|
192
+ | `CegraphError` | Base class for all cegraph errors. |
193
+ | `CausalCycleError` | A cycle is detected in the causal graph. |
194
+ | `CausalTypeError` | Output type of src node mismatches input type of dst node. |
195
+ | `CausalConstraintViolation` | A node's constraint function returns `False`. |
196
+ | `TracerOverflowWarning` | Ring buffer is full and overwriting old records (warning, not exception). |
197
+
198
+ ## Contributing
199
+
200
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, code style, and
201
+ pull request process. All contributions are welcome.
202
+
203
+ ## License
204
+
205
+ MIT -- see [LICENSE](LICENSE) for details.
@@ -0,0 +1,15 @@
1
+ cegraph/__init__.py,sha256=8aP_UZLShlmiOI-bs6GpupoJ5dhp9ROSTjlp-YxFT2o,1034
2
+ cegraph/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
3
+ cegraph/exceptions.py,sha256=fj7lGd-Tyy1ENVSyxX36y1MtQfbgRbKBKjJahRRXnsg,785
4
+ cegraph/causal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ cegraph/causal/counterfactual.py,sha256=lwaXMdZmF1hnx-vpvrWw0OfptTwBvqQLh-B-RRWuwDI,4626
6
+ cegraph/causal/optimizer.py,sha256=NJW873F-tGnAZ1fjzTam55DgWdh5VIXyBXLvio6cVkQ,3947
7
+ cegraph/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ cegraph/core/context.py,sha256=axCjkxv3WEAgJ5FoqXgmTnvQsTL4VEWxmNeeHoONBiA,1252
9
+ cegraph/core/graph.py,sha256=X9iRPLW_dQGfFpLYZ9Q0seY06-650NeABVqWOOF7wD4,4585
10
+ cegraph/core/node.py,sha256=8SBuIziaIZmknY7zD4VGKZbAy1FQ4aXsK4g88VH0UDY,2660
11
+ cegraph/core/tracer.py,sha256=ijpwQ-JykDcjJYGX0QXMUyp0hUiMOHzkwDR1im0R2yE,4314
12
+ cegraph-0.1.0.dist-info/METADATA,sha256=H9YWZYEjrcr4nwXEIqnQlWIlBBLXU4VElDnwmfuubh8,8554
13
+ cegraph-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
14
+ cegraph-0.1.0.dist-info/licenses/LICENSE,sha256=64rWKdq8_tV675lMWMg7IicCF_Qbnyx4R2NtqO9NfMo,1067
15
+ cegraph-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 devcegraph
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.