Skip to content

semonkhan/Statebits

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

2 Commits
ย 
ย 

Repository files navigation

Version Python License PyPI



โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—
โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ•šโ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ•šโ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘โ•šโ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•
โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—   โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—  โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—
โ•šโ•โ•โ•โ•โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•”โ•โ•โ•  โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•‘   โ•šโ•โ•โ•โ•โ–ˆโ–ˆโ•‘
โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•‘  โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•‘
โ•šโ•โ•โ•โ•โ•โ•โ•   โ•šโ•โ•   โ•šโ•โ•  โ•šโ•โ•   โ•šโ•โ•   โ•šโ•โ•โ•โ•โ•โ•โ•โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ•   โ•šโ•โ•   โ•šโ•โ•โ•โ•โ•โ•โ•

Causal computing for transparent, explainable state management

Every state change. Every reason. Every time.


๐Ÿ“ฆ Install ยท โšก Quick Start ยท ๐Ÿง  ML/AI ยท ๐Ÿข Enterprise ยท ๐Ÿ“– Docs


What is Statebits?

Traditional state management treats changes as black boxes โ€” values appear, disappear, and mutate with no record of why. Statebits changes that.

Every transition carries a reason, a confidence score, a timestamp, and full context. Your state becomes a story you can read, audit, query, and predict.

from statebits import Statebit

mood = Statebit(identity="user_mood", initial_value="neutral")
mood.transition("happy",   "User received good news", confidence=0.90)
mood.transition("excited", "User won a prize",        confidence=0.95)

print(mood.explain())  # Full causal history, human-readable

Why Statebits?

Traditional State Statebits
x = 42 โ€” no context x โ†’ 42 with reason, confidence, timestamp
Debugging is guesswork Full transition history to replay
Compliance is a nightmare Built-in audit trail with integrity checks
ML feels bolted on First-class LSTM, AutoML, anomaly detection
One machine, one state Redis-backed distributed state out of the box

Installation

pip install statebits              # Core
pip install statebits[ml]          # + LSTM, AutoML, anomaly detection, clustering
pip install statebits[enterprise]  # + RBAC, multi-tenancy, audit logging
pip install statebits[all]         # Everything
Full install options
pip install statebits[async_support]  # Async/await support
pip install statebits[distributed]    # Redis-backed distributed state
pip install statebits[streaming]      # WebSocket real-time streaming
pip install statebits[graphql]        # GraphQL API via FastAPI
pip install statebits[timeseries]     # InfluxDB / TimescaleDB backends
pip install statebits[encryption]     # AES-256 encrypted state
pip install statebits[visualization]  # Charts and graph export

Quick Start

Basic state with full causal tracking

from statebits import Statebit, ConfidenceLevel

temperature = Statebit(identity="room_temp", initial_value=20.0)

temperature.transition(22.0, "Heater turned on",  confidence=ConfidenceLevel.HIGH)
temperature.transition(25.0, "Target reached",    confidence=ConfidenceLevel.VERY_HIGH)
temperature.transition(24.0, "Slight cooling",    confidence=0.85)

# Query history
high_confidence = temperature.get_transitions_by_confidence(0.9)
stats = temperature.get_statistics()

# Rollback if needed
temperature.rollback(steps=1)

Fork โ†’ test โ†’ merge

# Non-destructive scenario testing
simulation = account.fork(reason="Testing withdrawal scenario")
simulation.transition(500, "Simulated withdrawal")

# Merge back only if simulation passed
account.merge(simulation, strategy='latest')

Observers and alerts

def alert_on_high_load(statebit, transition):
    if transition.to_value > 0.8:
        send_alert(f"โš ๏ธ High CPU: {transition.to_value:.0%}")

cpu = Statebit(identity="cpu_load", initial_value=0.2)
cpu.add_observer(alert_on_high_load)

Core Features

๐Ÿ” Transparent Transitions Every change tracked with reason, confidence, timestamp, tags, and context.

๐Ÿ“ฆ Collections & Batch Ops Group related statebits; apply transitions across all at once.

๐ŸŒฟ Fork & Merge Test scenarios on isolated forks; merge back when satisfied.

โช Rollback Undo the last N transitions with a single call.

๐Ÿ”’ Freeze & Lock Prevent mutations temporarily or permanently.

๐Ÿ”” Observers React to transitions in real-time with custom callbacks.

๐Ÿ’พ Serialization Export to JSON, CSV, or Pickle; restore with full fidelity.

๐Ÿ“Š Analysis Pattern detection, trend analysis, and statistical summaries.


Enhanced Features v0.2.0

โšก Async Support

from statebits import AsyncStatebit
import asyncio

async def main():
    sb = AsyncStatebit(identity="price", initial_value=100.0)
    await sb.transition(105.0, "Market moved up", confidence=0.88)

asyncio.run(main())

๐ŸŒ Distributed State (Redis)

from statebits import DistributedStatebit

async def main():
    sb = DistributedStatebit(
        identity="global_config",
        redis_url="redis://localhost:6379",
        initial_value={"feature_flags": {}}
    )
    await sb.connect()
    await sb.transition({"feature_flags": {"v2": True}}, "Feature flag enabled")
    await sb.disconnect()

๐Ÿ“ก Real-time Streaming

from statebits import StatebitsWebSocketServer

server = StatebitsWebSocketServer(host="0.0.0.0", port=8765)
server.register_statebit(my_statebit)
await server.start()  # Stream transitions to any WebSocket client

๐Ÿ”Œ GraphQL API

from statebits import create_graphql_router
from fastapi import FastAPI

app = FastAPI()
app.include_router(create_graphql_router(collection), prefix="/graphql")

๐Ÿ›ก๏ธ Encryption

from statebits import EncryptedStatebit, EncryptionManager

encryption = EncryptionManager(key_derivation_password="secret")
sensitive = EncryptedStatebit(
    identity="patient_record",
    initial_value={"diagnosis": "..."},
    encryption_manager=encryption
)

ML/AI Integration

No ML dependency required to get started. NLExplainer works out of the box. Heavier models need pip install statebits[ml].

๐Ÿ’ฌ Natural Language Explanations

from statebits import NLExplainer

explainer = NLExplainer()
print(explainer.summarize_history(sb))  # Human-readable summary
print(explainer.generate_explanation(sb))  # Full causal narrative

๐Ÿ”ฎ LSTM/Transformer Prediction

from statebits import SequencePredictor

predictor = SequencePredictor(model_type="lstm")
predictor.train(sb, epochs=50)

prediction = predictor.predict(sb)
print(f"Next value: {prediction.predicted_value}  (confidence: {prediction.confidence:.2f})")

๐Ÿšจ Anomaly Detection

from statebits import AnomalyDetector

detector = AnomalyDetector(contamination=0.05)
detector.fit(sb)

result = detector.detect(sb, transition_index=-1)
if result.is_anomaly:
    print(f"โš ๏ธ Anomaly score: {result.anomaly_score:.4f}")

๐Ÿค– AutoML

from statebits import AutoMLPredictor

automl = AutoMLPredictor()
results = automl.auto_select(sb)         # Tests all available models
prediction = automl.predict(sb)

print(f"Best model: {results['best_model']}")
print(f"Predicted:  {prediction.predicted_value}")

๐Ÿงฌ Reinforcement Learning

from statebits import RLAgent

agent = RLAgent(state_space_size=20, action_space_size=5)

for episode in range(100):
    state_idx = agent.get_state_index(sb)
    action    = agent.choose_action(state_idx)
    reward    = apply_action(sb, action)
    agent.update(state_idx, action, reward, agent.get_state_index(sb))

optimal = agent.get_optimal_action(sb)
Full ML feature list
Feature Class Description
NL Explanations NLExplainer No ML deps needed; summarizes history in plain English
Sequence Prediction SequencePredictor LSTM and Transformer models
Anomaly Detection AnomalyDetector Isolation Forest
Clustering StateClusterer K-Means and DBSCAN
AutoML AutoMLPredictor Automatically selects and tunes the best model
Explainable AI ExplainableAI SHAP-based feature importance
Reinforcement Learning RLAgent Q-learning for optimal transition policies

Enterprise Features

# Multi-tenancy
from statebits import MultiTenantManager, TenantContext

manager = MultiTenantManager()
tenant  = manager.create_tenant("acme_corp")

with TenantContext(tenant.tenant_id):
    sb = Statebit(identity="revenue", initial_value=0)

# Role-Based Access Control
from statebits import AccessControlManager, Permission

ac = AccessControlManager()
ac.create_user("alice", roles=["admin"])
ac.protect(sb, owner="alice")

if ac.check_permission("alice", sb, Permission.WRITE):
    sb.transition(1_000_000, "Q4 revenue", confidence=1.0)

# Audit Logging
from statebits import AuditLogger

logger = AuditLogger(storage="file")
logger.attach(sb)
report = logger.generate_compliance_report(sb.identity)

# Monitoring Dashboard
from statebits import MonitoringDashboard

dashboard = MonitoringDashboard(port=8080)
dashboard.register(sb)
await dashboard.start()  # Web UI at http://localhost:8080

Use Cases

Domain What Statebits solves
๐Ÿฆ Finance Immutable audit trails for transactions, anomaly detection for fraud, AutoML for risk scoring
๐Ÿฅ Healthcare Patient state monitoring with full context, compliance reporting, vitals anomaly detection
๐ŸŒก๏ธ IoT Distributed device state via Redis, LSTM sensor prediction, real-time WebSocket streaming
๐Ÿค– ML Ops Model training tracking, SHAP-based prediction explanation, experiment management
๐Ÿšš Supply Chain End-to-end shipment tracking with complete transparency and delay prediction

CLI

statebits analyze   state.json                    # Statistical analysis
statebits visualize state.json --output graph.png # Export history graph
statebits validate  state.json                    # Integrity check
statebits export    state.json --format csv       # Convert format
statebits compare   state1.json state2.json       # Diff two statebits

Performance

Operation Benchmark
Single transition < 1ms
Query over 1,000 transitions < 10ms
ML model training 5โ€“20 seconds
Scale Millions of transitions

Security: AES-256 encryption ยท SHA integrity checksums ยท Thread-safe ยท Secure key management


Project Structure

statebits/
โ”œโ”€โ”€ core.py            # Statebit, StateTransition, collections
โ”œโ”€โ”€ advanced.py        # Learning, Temporal, Persistent, Network, Scheduler
โ”œโ”€โ”€ async_support.py   # AsyncStatebit
โ”œโ”€โ”€ distributed.py     # Redis-backed DistributedStatebit
โ”œโ”€โ”€ streaming.py       # WebSocket server
โ”œโ”€โ”€ graphql_api.py     # GraphQL via Strawberry + FastAPI
โ”œโ”€โ”€ timeseries.py      # InfluxDB / TimescaleDB backends
โ”œโ”€โ”€ encryption.py      # AES-256 EncryptedStatebit
โ”œโ”€โ”€ ml_integration.py  # LSTM, AutoML, anomaly, clustering, RL, SHAP
โ”œโ”€โ”€ utils.py           # Serializer, Analyzer, Validator, Comparator
โ”œโ”€โ”€ config.py          # Global configuration
โ””โ”€โ”€ performance.py     # Monitoring and profiling

Coverage

34 working examples  ยท  100+ test cases  ยท  49+ major features

Tests span core, async, distributed, streaming, GraphQL, time-series, encryption, ML, and backward compatibility.

Links

๐ŸŒ Homepage https://statebits.xyz
๐Ÿ“– Documentation https://statebits.xyz
๐Ÿ“ฆ PyPI https://pypi.org/project/statebits/
๐Ÿ› Issues https://github.com/semonkhan/Statebits/issues
๐Ÿ’ฌ Repository https://github.com/semonkhan/Statebits

License

MIT ยฉ Semon Khan


Statebits โ€” because every change deserves an explanation.

About

A causal computing framework for transparent and explainable state management.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors