Skip to main content

A causal computing framework for transparent and explainable state management

Project description

Statebits: Transparent State Management for Python

A causal computing framework that makes every state change transparent, explainable, and auditable.

PyPI version Python 3.8+ License: MIT Build Status

What is Statebits?

Statebits transforms how applications manage state by bringing complete transparency to every state transition. Instead of treating state changes as black boxes, Statebits records the complete context, reasoning, and confidence level of every transition.

Built by Semon Khan, this framework combines causal computing principles with modern ML/AI capabilities to create a state management system that's not just functional, but also explainable and auditable.

Why Choose Statebits?

  • Transparent: Every state change is tracked with full context and reasoning
  • Auditable: Complete immutable history with integrity verification
  • Explainable: Built-in tools to understand why states changed
  • Intelligent: ML-powered predictions based on historical patterns
  • Scalable: From simple tracking to distributed enterprise systems
  • Flexible: Core functionality + optional advanced features

Installation

Get started in seconds with pip:

pip install statebits

For specific feature sets:

pip install statebits[ml]           # ML/AI: LSTM, Transformers, AutoML, etc.
pip install statebits[enterprise]   # Enterprise: Multi-tenancy, RBAC, Audit
pip install statebits[distributed]  # Distributed: Redis-backed state
pip install statebits[all]          # Everything

Quick Start - 60 Seconds

from statebits import Statebit

# Create a stateful object
account = Statebit(identity="checking_account", initial_value=1000.0)

# Track state changes with context
account.transition(1500.0, "Deposit received", confidence=1.0, tags=["deposit"])
account.transition(1450.0, "ATM withdrawal", confidence=1.0, tags=["withdrawal"])

# Get current state
print(f"Balance: ${account.value}")

# View complete history with explanations
print(account.explain())

Output:

Balance: $1450.0

State History:
1. $1000.0 → $1500.0 (Deposit received) [100% confidence]
2. $1500.0 → $1450.0 (ATM withdrawal) [100% confidence]

Core Features

1. Transparent State Transitions

Every state change is tracked with full context:

from statebits import Statebit, ConfidenceLevel

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

# Transitions with confidence levels
temperature.transition(22.0, "Heater turned on", confidence=ConfidenceLevel.HIGH)
temperature.transition(25.0, "Target reached", confidence=ConfidenceLevel.VERY_HIGH)

# Query by confidence
high_confidence = temperature.get_transitions_by_confidence(0.8)

2. Collections and Batch Operations

Manage multiple statebits together:

from statebits import StatebitsCollection

sensors = StatebitsCollection(name="IoT_Sensors")
sensors.add(temp_sensor)
sensors.add(humidity_sensor)

# Batch transitions
transitions = [
    {'new_value': i, 'reason': f'Update {i}', 'confidence': 0.9}
    for i in range(10)
]
sensor.batch_transition(transitions)

3. Learning and Adaptation

Statebits that learn from feedback:

from statebits import LearningStatebit

model = LearningStatebit(identity="ml_accuracy", initial_value=0.75)
model.set_learning_rate(0.1)

# Transition with feedback
model.transition(0.82, "Training iteration 1", confidence=0.8)
model.adapt_reasoning({'success': True, 'error_magnitude': 0.05})

# Get learning insights
summary = model.get_learning_summary()
print(f"Is confident: {summary['is_confident']}")

4. Forking and Merging

Test scenarios without affecting the main state:

# Fork for simulation
simulation = original.fork(reason="Testing withdrawal scenario")
simulation.transition(100, "Simulated withdrawal")

# Merge back if successful
original.merge(simulation, strategy='latest')

5. Serialization and Persistence

Save and restore statebits:

from statebits import StatebitsSerializer, PersistentStatebit

# Serialize to JSON
json_data = StatebitsSerializer.to_json(statebit)

# Deserialize
restored = StatebitsSerializer.from_json(json_data)

# Auto-save to file
persistent = PersistentStatebit(
    identity="auto_saved",
    initial_value=0,
    filepath="state.json"
)

6. Analysis and Insights

Analyze patterns and predict future states:

from statebits import StatebitsAnalyzer, StatebitsML

# Analyze transitions
analyzer = StatebitsAnalyzer()
analysis = analyzer.analyze_transitions(statebit)
print(f"Average confidence: {analysis['average_confidence']}")

# Predict next state
ml = StatebitsML()
prediction = ml.predict_next_state(statebit)
print(f"Predicted: {prediction['prediction']}")

7. Network and Dependencies

Model complex relationships:

from statebits import StatebitsNetwork

network = StatebitsNetwork()
network.add_statebit(sensor1)
network.add_statebit(sensor2)
network.add_dependency(sensor1, sensor2, weight=0.8)

# Propagate changes
network.propagate_change(sensor1)

Enhanced Features (v0.2.0)

Async Support

Work with statebits asynchronously:

from statebits import AsyncStatebit
import asyncio

async def main():
    mood = AsyncStatebit(identity="user_mood", initial_value="neutral")
    await mood.transition("happy", "Good news", confidence=0.9)
    print(f"Current: {mood.value}")

asyncio.run(main())

Distributed State (Redis)

Share state across multiple processes or servers:

from statebits import DistributedStatebit

async def main():
    mood = DistributedStatebit(
        identity="shared_mood",
        redis_url="redis://localhost:6379",
        initial_value="neutral"
    )
    
    await mood.connect()
    await mood.transition("happy", "Distributed update")
    await mood.disconnect()

asyncio.run(main())

Real-time Streaming (WebSocket)

Stream state changes in real-time:

from statebits import StatebitsWebSocketServer

server = StatebitsWebSocketServer(host="localhost", port=8765)
server.register_statebit(my_statebit)
await server.start()

GraphQL API

Expose statebits via GraphQL:

from statebits import create_graphql_router
from fastapi import FastAPI

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

Time-Series Storage

Store state history in time-series databases:

from statebits import InfluxDBBackend, TimescaleDBBackend

# InfluxDB
influx = InfluxDBBackend(
    url="http://localhost:8086",
    token="my-token",
    org="my-org",
    bucket="statebits"
)

# TimescaleDB
timescale = TimescaleDBBackend(
    host="localhost",
    database="statebits",
    user="postgres",
    password="password"
)

await influx.store_transition(statebit, transition)

Encryption

Encrypt sensitive state data:

from statebits import EncryptedStatebit, EncryptionManager

encryption = EncryptionManager(key_derivation_password="secret")
sensitive = EncryptedStatebit(
    identity="sensitive_data",
    initial_value="secret-value",
    encryption_manager=encryption
)

await sensitive.transition("new-secret", "Update")
decrypted = sensitive.get_value()

Enterprise Features

Multi-tenancy

Isolate data across multiple tenants:

from statebits import MultiTenantManager, TenantContext

manager = MultiTenantManager()
tenant = manager.create_tenant("acme_corp", max_statebits=1000)

with TenantContext(tenant.tenant_id):
    sb = Statebit(identity="tenant_data", initial_value=100)
    sb.transition(150, "Tenant update", confidence=0.9)

Access Control (RBAC)

Role-based permissions:

from statebits import AccessControlManager, Role, Permission

ac = AccessControlManager()
ac.create_role("admin", [Permission.READ, Permission.WRITE, Permission.DELETE])
ac.create_user("alice", roles=["admin"])

sb = Statebit(identity="protected", initial_value=100)
ac.protect(sb, owner="alice")

if ac.check_permission("alice", sb, Permission.WRITE):
    sb.transition(150, "Authorized update", confidence=0.9)

Audit Logging

Comprehensive audit trails:

from statebits import AuditLogger

logger = AuditLogger(storage="file", filepath="audit.log")
sb = Statebit(identity="audited", initial_value=1000)
logger.attach(sb)

# All transitions are automatically logged
sb.transition(1500, "Deposit", confidence=1.0, metadata={"user": "alice"})

# Generate compliance reports
report = logger.generate_compliance_report(sb.identity, start_date, end_date)

Backup and Restore

Automated disaster recovery:

from statebits import BackupManager, BackupStrategy

backup_mgr = BackupManager(
    strategy=BackupStrategy.INCREMENTAL,
    schedule="0 2 * * *",  # Daily at 2 AM
    retention_days=30
)

backup_mgr.register(sb)
backup_id = await backup_mgr.create_backup("pre_migration")

# Restore when needed
restored = await backup_mgr.restore_backup(backup_id)

Monitoring Dashboard

Real-time web dashboard:

from statebits import MonitoringDashboard

dashboard = MonitoringDashboard(host="0.0.0.0", port=8080)
dashboard.register(cpu, category="system")
dashboard.add_widget("line_chart", title="CPU Usage", statebit=cpu.identity)

await dashboard.start()
# Access at http://localhost:8080

Alerting System

Configurable alerts:

from statebits import AlertingSystem, Alert, AlertCondition

alerts = AlertingSystem()
alerts.add_channel("email", {"recipients": ["admin@example.com"]})

critical_alert = Alert(
    name="high_temp",
    condition=AlertCondition(field="value", operator=">", threshold=85),
    severity="critical",
    channels=["email", "slack"]
)

alerts.register(temperature, critical_alert)

Data Retention

Automated archival and cleanup:

from statebits import DataRetentionManager, RetentionPolicy

retention = DataRetentionManager()
policy = RetentionPolicy(
    retention_days=365,
    archive_after_days=90,
    compliance_mode=True
)

retention.apply_policy(financial_data, policy)
await retention.run_retention_check()

AI/ML Integration

Natural Language Explanations

Generate human-readable explanations for state transitions:

from statebits import NLExplainer

explainer = NLExplainer()

# Explain a single transition
explanation = explainer.generate_explanation(statebit, transition_index=-1)
print(explanation)

# Analyze patterns
pattern = explainer.explain_pattern(statebit, pattern_type="trend")
print(pattern)

# Summarize history
summary = explainer.summarize_history(statebit, max_transitions=10)
print(summary)

LSTM/RNN Sequence Prediction

Predict future states using deep learning:

from statebits import SequencePredictor

# Create and train LSTM model
predictor = SequencePredictor(model_type="lstm", hidden_size=64, num_layers=2)
predictor.train(statebit, sequence_length=10, epochs=50)

# Predict next state
prediction = predictor.predict(statebit)
print(f"Predicted: {prediction.predicted_value}")
print(f"Confidence: {prediction.confidence}")

Transformer Models

Use transformer architecture for complex patterns:

from statebits import SequencePredictor

# Create and train Transformer model
predictor = SequencePredictor(
    model_type="transformer",
    d_model=64,
    nhead=4,
    num_layers=2
)
predictor.train(statebit, sequence_length=10, epochs=50)

# Make predictions
prediction = predictor.predict(statebit)

Anomaly Detection

Detect unusual state transitions:

from statebits import AnomalyDetector

# Train detector
detector = AnomalyDetector(method="isolation_forest", contamination=0.1)
detector.fit(statebit)

# Detect anomalies
result = detector.detect(statebit, transition_index=-1)
print(f"Is anomaly: {result.is_anomaly}")
print(f"Score: {result.anomaly_score}")
print(f"Explanation: {result.explanation}")

State Clustering

Group similar states together:

from statebits import StateClusterer

# Train clusterer
clusterer = StateClusterer(method="kmeans", n_clusters=3)
clusterer.fit(statebit)

# Get cluster assignments
clusters = clusterer.get_all_clusters(statebit)
print(f"Cluster distribution: {dict((i, clusters.count(i)) for i in set(clusters))}")

# Predict cluster for new transition
cluster_info = clusterer.predict_cluster(statebit, transition_index=-1)
print(f"Cluster: {cluster_info['cluster']}")

AutoML

Automatic model selection and hyperparameter tuning:

from statebits import AutoMLPredictor

# Automatically select best model
automl = AutoMLPredictor()
results = automl.auto_select(statebit, test_size=0.2)

print(f"Best model: {results['best_model']}")
print(f"Best score: {results['best_score']}")

# Make predictions with best model
prediction = automl.predict(statebit)
print(f"Predicted: {prediction.predicted_value}")

Explainable AI (SHAP)

Explain model predictions with SHAP values:

from statebits import ExplainableAI

explainer = ExplainableAI(method="shap")
explanation = explainer.explain_prediction(
    model,
    statebit,
    feature_names=["confidence", "reason_length", "tags_count"]
)

# View feature importance
for exp in explanation["explanations"]:
    print(f"{exp['feature']}: {exp['importance']:.4f}")

Reinforcement Learning

Learn optimal state transitions:

from statebits import RLAgent

# Create RL agent
agent = RLAgent(state_space_size=20, action_space_size=5, learning_rate=0.1)

# Training loop
for episode in range(100):
    state_idx = agent.get_state_index(statebit)
    action = agent.choose_action(state_idx)
    
    # Apply action and get reward
    reward = apply_action(statebit, action)
    next_state_idx = agent.get_state_index(statebit)
    
    # Update Q-table
    agent.update(state_idx, action, reward, next_state_idx)

# Get optimal action
optimal = agent.get_optimal_action(statebit)
print(f"Optimal action: {optimal['action']}")

Combined ML Pipeline

Use multiple ML techniques together:

from statebits import (
    NLExplainer,
    AnomalyDetector,
    StateClusterer,
    AutoMLPredictor
)

# 1. Natural language summary
explainer = NLExplainer()
summary = explainer.summarize_history(statebit)

# 2. Detect anomalies
detector = AnomalyDetector()
detector.fit(statebit)
anomalies = [i for i in range(len(statebit.history)) 
             if detector.detect(statebit, i).is_anomaly]

# 3. Cluster states
clusterer = StateClusterer(n_clusters=3)
clusterer.fit(statebit)
clusters = clusterer.get_all_clusters(statebit)

# 4. Predict future
automl = AutoMLPredictor()
automl.auto_select(statebit)
prediction = automl.predict(statebit)

print(f"Summary: {summary}")
print(f"Anomalies: {len(anomalies)}")
print(f"Clusters: {set(clusters)}")
print(f"Prediction: {prediction.predicted_value}")

Advanced Configuration

Configure all features centrally:

from statebits import configure_v2, RedisConfig, EncryptionConfig

configure_v2(
    redis=RedisConfig(
        url="redis://localhost:6379",
        namespace="myapp",
        ttl=3600
    ),
    encryption=EncryptionConfig(
        enabled=True,
        key_source="env",
        key_env_var="STATEBITS_KEY"
    )
)

Performance Monitoring

Built-in performance tracking:

from statebits import get_monitor, monitor_performance

@monitor_performance("custom_operation")
def my_function():
    # Your code here
    pass

# Get performance report
monitor = get_monitor()
monitor.print_report()

Logging and Debugging

Comprehensive logging system:

from statebits import get_logger, set_log_level
import logging

logger = get_logger()
set_log_level(logging.DEBUG)

# Logs are automatically generated for all operations

Use Cases

AI and Machine Learning

Track model training, explain predictions, and maintain audit trails:

model_accuracy = LearningStatebit(identity="model_v1", initial_value=0.75)
model_accuracy.transition(0.82, "Epoch 10 completed", confidence=0.85)
model_accuracy.adapt_reasoning({'loss': 0.15, 'validation_score': 0.83})

Finance and Trading

Maintain transparent audit trails for transactions:

account = Statebit(identity="account_123", initial_value=1000.0)
account.transition(1500.0, "Deposit: Wire transfer", confidence=1.0, tags=['deposit'])
account.transition(1450.0, "Withdrawal: ATM", confidence=1.0, tags=['withdrawal'])

# Full audit trail
print(account.explain(format='text'))

Healthcare

Track patient states with full context and compliance:

patient_status = Statebit(identity="patient_001", initial_value="stable")
patient_status.transition("monitoring", "Vitals show irregularity", confidence=0.7)
patient_status.transition("stable", "Vitals normalized", confidence=0.9)

IoT and Smart Systems

Manage device states across distributed systems:

thermostat = DistributedStatebit(
    identity="thermostat_living_room",
    redis_url="redis://iot-hub:6379",
    initial_value=20.0
)
await thermostat.transition(22.0, "User adjusted temperature")

Supply Chain

Track goods with complete transparency:

shipment = Statebit(identity="shipment_789", initial_value="warehouse")
shipment.transition("in_transit", "Loaded on truck #42", confidence=1.0)
shipment.transition("delivered", "Signed by recipient", confidence=1.0)

CLI Tool

Statebits includes a command-line interface:

# Analyze a saved statebit
statebits analyze state.json

# Visualize state history
statebits visualize state.json --output graph.png

# Validate statebit integrity
statebits validate state.json

API Reference

Core Classes

  • Statebit: Basic state management with causal tracking
  • StateTransition: Represents a single state change
  • StatebitsCollection: Manage multiple statebits
  • LearningStatebit: Adaptive statebit with learning capabilities
  • TemporalStatebit: Time-aware state management
  • PersistentStatebit: Auto-saving statebit

Enhanced Classes (v0.2.0)

  • AsyncStatebit: Async/await support
  • DistributedStatebit: Redis-backed distributed state
  • EncryptedStatebit: Encrypted state storage
  • StatebitsWebSocketServer: Real-time streaming
  • TimeSeriesBackend: Time-series database integration

ML/AI Classes

  • SequencePredictor: LSTM/RNN and Transformer models
  • AnomalyDetector: Isolation Forest anomaly detection
  • StateClusterer: K-Means and DBSCAN clustering
  • AutoMLPredictor: Automatic model selection
  • ExplainableAI: SHAP-based explanations
  • RLAgent: Q-learning reinforcement learning
  • NLExplainer: Natural language explanations

Enterprise Classes

  • MultiTenantManager: Multi-tenancy management
  • AccessControlManager: RBAC implementation
  • AuditLogger: Comprehensive audit logging
  • BackupManager: Automated backup and restore
  • MonitoringDashboard: Web-based monitoring
  • AlertingSystem: Configurable alerting
  • DataRetentionManager: Data retention policies

Utilities

  • StatebitsSerializer: JSON/pickle serialization
  • StatebitsAnalyzer: Pattern analysis
  • StatebitsValidator: Validation utilities
  • StatebitsComparator: Compare statebits
  • StatebitsNetwork: Model dependencies
  • StatebitsML: Predict future states

Configuration

Configure Statebits globally:

from statebits import configure

configure(
    max_history_size=1000,
    auto_prune_history=True,
    default_confidence=0.8,
    enable_integrity_checks=True,
    timestamp_precision=6
)

Real-World Use Cases

Financial Services

  • Transaction auditing with complete history
  • Fraud detection via anomaly detection
  • Compliance reporting (SOX, PCI-DSS)
  • Account state transitions with audit trails

Healthcare

  • Patient state monitoring
  • Vital signs anomaly alerts
  • HIPAA-compliant audit logging
  • Treatment history with full reasoning

IoT & Smart Systems

  • Distributed device state management
  • Predictive maintenance using LSTM
  • Real-time monitoring dashboards
  • Automated alerting for failures

AI/ML Development

  • Model training state tracking
  • Experiment reproducibility
  • Prediction explanations
  • Performance monitoring

SaaS Applications

  • Multi-tenant data isolation
  • User action auditing
  • Feature usage tracking
  • Compliance reporting

Full Documentation

For comprehensive features, examples, and API reference:

License

Statebits is released under the MIT License. See LICENSE for details.

Links

Author

Semon Khan
Email: semon.2444@gmail.com

Changing Computation Forever

Statebits represents a paradigm shift in state management and computation. By providing transparency and explainability at every step, it addresses critical challenges in modern computing:

  • Trust: Build systems users can trust through complete transparency
  • Accountability: Every change is tracked with full context and reasoning
  • Debugging: Understand exactly why and how states changed
  • Compliance: Meet audit requirements with comprehensive state history
  • Collaboration: Share understanding across teams and systems

Whether you're building AI systems, financial applications, healthcare platforms, or IoT networks, Statebits provides the foundation for transparent, explainable, and trustworthy state management.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

statebits-0.2.1.tar.gz (114.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

statebits-0.2.1-py3-none-any.whl (74.0 kB view details)

Uploaded Python 3

File details

Details for the file statebits-0.2.1.tar.gz.

File metadata

  • Download URL: statebits-0.2.1.tar.gz
  • Upload date:
  • Size: 114.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for statebits-0.2.1.tar.gz
Algorithm Hash digest
SHA256 119aa2daf06f7dbacf300a8d79aa433dfb92b86b9048ec31eb45872735045291
MD5 345f3bea3e6e34df58dd713a006edaf5
BLAKE2b-256 c0c6c257611b4b5629ef9bfd1876d57aa43da01577499e0789d94054f921770c

See more details on using hashes here.

File details

Details for the file statebits-0.2.1-py3-none-any.whl.

File metadata

  • Download URL: statebits-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 74.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for statebits-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 18e2e757cb0aaf86f6be9cc333409818bcee15ba2cf4898de8385bedebb13b87
MD5 d630af8978cbf3c863f162cc1b7adf27
BLAKE2b-256 538f3d0da677ad777cc979889c9983b45cb1a9373425e4295bc80f620042f1f4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page