Documentation

Complete guide to Statebits — transparent state management with causal computing, ML/AI capabilities, and enterprise features.

Quick Start

Get Statebits running in 60 seconds.

Installation

Terminal
pip install statebits

First Statebit

Python
from statebits import Statebit # Create a statebit account = Statebit(identity="checking", initial_value=1000.0) # Track changes with context account.transition(1500.0, "Deposit received", confidence=1.0) account.transition(1450.0, "ATM withdrawal", confidence=1.0) # Get current value print(f"Balance: ${account.value}") # View full history print(account.explain())

That's it! You now have a state with complete transparency and audit trail.

Installation

Basic Setup

Terminal
pip install statebits

Feature-Specific Installation

Install with specific feature sets:

Terminal
# With ML/AI capabilities pip install statebits[ml] # With distributed state (Redis) pip install statebits[distributed] # With async support pip install statebits[async_support] # Everything pip install statebits[all]

Basic Usage

Create a Statebit

Python
from statebits import Statebit # Create with identity and initial value mood = Statebit( identity="user_mood", initial_value="neutral" )

Make Transitions

Python
# Simple transition mood.transition("happy", "Got good news") # With confidence level mood.transition( "excited", "Won a prize", confidence=0.95 ) # With tags for categorization mood.transition( "relaxed", "Meditation session", tags=["wellness", "scheduled"] )

Access History

Python
# Get current value current = mood.value # Access full history for transition in mood.history: print(f"{transition.from_value} → {transition.to_value}") print(f"Reason: {transition.reason}") print(f"Confidence: {transition.confidence}") # Get explanation print(mood.explain())

State Management

A Statebit is the core unit of transparent state management. It maintains not just the current value, but the complete history of how it got there.

Key Properties

  • Identity: Unique identifier for the statebit
  • Value: Current state value (any type)
  • History: Immutable record of all transitions
  • Metadata: Tags, confidence levels, timestamps
  • Integrity: Checksums for verification

Example: Account Management

Python
from statebits import Statebit # Create account with initial balance account = Statebit( identity="account_001", initial_value=1000.0 ) # Record financial transactions account.transition( 1500.0, "Direct deposit salary", confidence=1.0, tags=["income", "payroll"] ) account.transition( 1200.0, "Rent payment", confidence=1.0, tags=["expense", "recurring"] ) # Full audit trail available print(account.explain(depth=3))

Transitions

Every state change is a first-class record with full context.

Transition Structure

  • from_value: Previous state
  • to_value: New state
  • reason: Why the change happened
  • confidence: Certainty level (0.0-1.0)
  • timestamp: When it happened
  • tags: Categories for filtering
  • metadata: Additional context

Making Transitions

Python
# Basic transition sensor.transition(25.5, "Temperature reading") # With all parameters sensor.transition( new_value=25.5, reason="Ambient temperature sensor reading", confidence=0.9, tags=["sensor", "automated"], metadata={"location": "room_a", "source": "mqtt"} )

Batch Transitions

Update multiple states efficiently:

Python
# Define multiple transitions transitions = [ {'new_value': i, 'reason': f'Update {i}', 'confidence': 0.9} for i in range(10) ] # Apply all at once statebit.batch_transition(transitions)

Confidence Levels

Express uncertainty about state changes. Confidence helps you understand the reliability of state transitions.

Predefined Levels

VERY_LOW (0.1)

Highly uncertain, requires verification

LOW (0.3)

Somewhat uncertain, use with caution

MEDIUM (0.6)

Reasonable confidence, acceptable

HIGH (0.8)

High confidence, generally reliable

VERY_HIGH (0.95)

Very high confidence, trustworthy

CERTAIN (1.0)

Absolute certainty

Using Confidence Levels

Python
from statebits import ConfidenceLevel # Using predefined constants sensor.transition( 25.0, "Sensor reading", confidence=ConfidenceLevel.HIGH ) # Using numeric values sensor.transition(26.0, "Predicted value", confidence=0.7) # Query by confidence high_conf = sensor.get_transitions_by_confidence(0.8)

Collections

Manage multiple related statebits together with group operations and statistics.

Create and Use Collections

Python
from statebits import StatebitsCollection # Create collection sensors = StatebitsCollection(name="IoT_Sensors") # Add statebits sensors.add(temp_sensor) sensors.add(humidity_sensor) sensors.add(pressure_sensor) # Get collection statistics stats = sensors.get_collection_statistics() print(f"Total transitions: {stats['total_transitions']}") print(f"Avg confidence: {stats['average_confidence']}") # Query across collection recent = sensors.get_recent_transitions(limit=10)

Forking & Merging

Test scenarios safely without affecting production state.

Fork for Simulation

Python
# Create a fork simulation = original.fork(reason="Testing withdrawal scenario") # Make changes in fork simulation.transition(100, "Simulated withdrawal") simulation.transition(80, "Simulated fee") # Merge back if successful original.merge(simulation, strategy='latest')

Merge Strategies

  • latest: Use most recent value
  • highest_confidence: Use highest confidence transition
  • custom: Custom merge logic

Async Support

Work with statebits asynchronously for better concurrency.

Async Statebit

Python
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) await mood.transition("excited", "Won prize", confidence=0.95) print(f"Current: {mood.value}") asyncio.run(main())

Distributed State

Share state across multiple processes or servers using Redis.

Setup Distributed Statebit

Python
from statebits import DistributedStatebit import asyncio async def main(): mood = DistributedStatebit( identity="shared_mood", redis_url="redis://localhost:6379", initial_value="neutral" ) await mood.connect() try: await mood.transition("happy", "Distributed update") finally: await mood.disconnect() asyncio.run(main())

ML & AI Integration

Statebits includes powerful ML/AI capabilities for predictions, anomaly detection, and explanations.

Available ML Features

Natural Language

Generate human-readable explanations without ML dependencies

Predictions

LSTM, Transformer, and AutoML models predict future states

Anomaly Detection

Identify unusual state transitions automatically

Clustering

Group similar states together using K-Means or DBSCAN

AutoML

Automatic model selection and hyperparameter tuning

Explainable AI

SHAP values explain model predictions

Predictions

Predict future states using deep learning models.

LSTM Prediction

Python
from statebits import SequencePredictor # Create and train LSTM predictor = SequencePredictor( model_type="lstm", hidden_size=64, num_layers=2 ) # Train on history 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

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

Anomaly Detection

Detect unusual state transitions automatically.

Python
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}")

Use Cases

  • Fraud detection in financial transactions
  • System monitoring and alerting
  • Quality control in manufacturing
  • Security threat detection

Clustering

Group similar states together.

Python
from statebits import StateClusterer # Train clusterer clusterer = StateClusterer( method="kmeans", n_clusters=3 ) clusterer.fit(statebit) # Get cluster distribution clusters = clusterer.get_all_clusters(statebit) print(f"Distribution: {clusters}") # Predict cluster for new transition cluster_info = clusterer.predict_cluster(statebit, transition_index=-1) print(f"Cluster: {cluster_info['cluster']}")

Multi-Tenancy

Isolate data across multiple customers with complete data separation.

Python
from statebits import TenantManager # Create tenant manager manager = TenantManager() # Create tenant tenant = manager.create_tenant( "acme_corp", max_statebits=1000 ) # Use tenant context with manager.tenant_context(tenant.tenant_id): sb = Statebit(identity="tenant_data", initial_value=100) sb.transition(150, "Tenant update")

Access Control (RBAC)

Control who can read, write, and manage statebits.

Python
from statebits import AccessControl, Permission # Create access control ac = AccessControl() # Create users ac.create_user("alice", roles=["admin"]) ac.create_user("bob", roles=["analyst"]) # Protect statebit sb = Statebit(identity="protected", initial_value=100) ac.protect_statebit(sb, owner="alice") # Check permissions if ac.check_permission("alice", sb, Permission.WRITE): sb.transition(150, "Authorized update")

Audit Logging

Comprehensive audit trails for compliance and debugging.

Python
from statebits import AuditLogger # Create logger logger = AuditLogger(storage="file", filepath="audit.log") # Attach to statebit sb = Statebit(identity="audited", initial_value=1000) logger.attach(sb) # Transitions automatically logged sb.transition(1500, "Deposit", metadata={"user": "alice"}) # Generate compliance report report = logger.generate_compliance_report(sb.identity)

Backup & Restore

Automated backup and disaster recovery.

Python
from statebits import BackupManager # Create backup manager backup_mgr = BackupManager(strategy="incremental") # Register statebit backup_mgr.register(sb) # Create backup backup_id = await backup_mgr.create_backup("pre_migration") # Restore if needed restored = await backup_mgr.restore_backup(backup_id)

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
  • TemporalStatebit: Time-aware state management

Enhanced Classes (v0.2.0)

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

ML/AI Classes

  • SequencePredictor: LSTM/Transformer models
  • AnomalyDetector: Detect anomalies
  • StateClusterer: K-Means and DBSCAN clustering
  • AutoMLPredictor: Automatic model selection
  • NLExplainer: Natural language explanations

Enterprise Classes

  • TenantManager: Multi-tenancy management
  • AccessControl: RBAC implementation
  • AuditLogger: Audit logging
  • BackupManager: Backup and restore
  • MonitoringDashboard: Web-based monitoring

FAQ

What's the difference between a Statebit and a variable?

A Statebit maintains the complete history of how a value changed, including the reason, confidence level, and timing of each change. A variable just holds a value. This makes Statebits ideal for auditable systems where you need to understand not just what the current state is, but how it got there.

Can I use Statebits in production?

Yes. Statebits is production-ready with full test coverage, comprehensive documentation, and enterprise features like audit logging, backup/restore, and access control.

What types of values can Statebits hold?

Any Python type: strings, numbers, booleans, lists, dictionaries, objects, etc. The framework is type-agnostic.

How do I query state history?

Use built-in methods like get_transitions_by_confidence(), get_transitions_by_tag(), query(), and get_transitions_in_range().

Is there a performance impact?

Minimal. Transitions take <1ms, queries <10ms for 1000 transitions. Statebits scales to millions of transitions.

How do I get started with ML?

Start with NLExplainer for simple explanations (no ML dependencies), then try AutoMLPredictor for automatic model selection, or use specific models like SequencePredictor.

Can I use Statebits with my async code?

Yes. Use AsyncStatebit for async/await support.

How do I share state across processes?

Use DistributedStatebit with Redis for distributed state management.