Environment Variables Reference
Environment Variables Reference¶
Back to Home
This document provides a comprehensive reference for all environment variables used in the ByteBiota digital evolution system.
Overview {#overview}¶
ByteBiota uses environment variables for configuration management, allowing flexible deployment across different environments without code changes. Variables can be set via:
- System environment variables
.env
files (automatically loaded from project root or parent directories)- Systemd/supervisor environment settings
- Command-line overrides
Configuration Levels {#configuration-levels}¶
ByteBiota environment variables are organized into three levels based on how frequently they need to be changed:
Core Variables {#core-variables}¶
Essential variables that users commonly adjust for different deployment scenarios. These control basic functionality and resource allocation.
Standard Variables {#standard-variables}¶
Important variables for fine-tuning system behavior. These are typically set once per deployment environment.
Advanced Variables {#advanced-variables}¶
Low-level variables that rarely need to be changed. These control internal system behavior and are usually left at default values.
Auto-Detection {#auto-detection}¶
ByteBiota now includes automatic resource detection for optimal performance:
- Resource Detection: Automatically detects CPU cores, available memory, and disk space
- Optimal Settings: Calculates appropriate resource limits, batch sizes, and network parameters
- CLI Override: All auto-detected values can be overridden via command-line arguments
- Preset Support: Use
--preset auto
to enable automatic resource detection
Platform Compatibility {#platform-compatibility}¶
ByteBiota workers are designed to run cross-platform on Windows, macOS, and Linux:
Supported Platforms¶
- Windows 10/11: Full support with Windows-specific process priority classes
- macOS 12+: Full support with Unix nice levels (may require elevated permissions for negative values)
- Linux (Ubuntu 20.04+): Full support with standard Unix nice levels
Platform-Specific Behavior¶
- Process Priority: Windows uses priority classes (IDLE, BELOW_NORMAL, NORMAL, ABOVE_NORMAL, HIGH), while Unix systems use nice levels (-20 to 19)
- CPU Detection: Cross-platform detection using
os.cpu_count()
,multiprocessing.cpu_count()
, and platform-specific fallbacks - Event Loops: Windows uses ProactorEventLoop by default (Python 3.8+), Unix systems use SelectorEventLoop
- File Paths: All paths use
pathlib.Path
for cross-platform compatibility
Environment Variables¶
All environment variables work consistently across platforms. No platform-specific variable names are used.
Adaptive Network Configuration {#adaptive-network-configuration}¶
The system now includes adaptive network configuration that improves over time:
- Connection Quality Tracking: Monitors response times, error rates, and success rates
- Automatic Adjustment: Adjusts polling intervals and heartbeat frequencies based on network conditions
- Conservative Start: Begins with conservative defaults and optimizes based on actual performance
- Transparent Logging: All network parameter adjustments are logged for visibility
Evolution Configuration Guide {#evolution-configuration}¶
Energy Economy Principles {#energy-economy}¶
The energy economy is critical for sustainable digital evolution. Organisms must be able to harvest more energy than they consume to survive and reproduce.
Key Parameters:
- MEMORY_RENT_PER_BYTE
: Cost per byte of memory per cycle (default: 0.0001)
- ENV_HARVEST_YIELD
: Energy gained from harvest operations (default: 100)
- CPU_COST_PER_INSTRUCTION
: Energy cost per CPU instruction (default: 0.005)
- ENERGY_INITIAL
: Starting energy for new organisms (default: 500)
Balancing Guidelines:
- Memory rent should be low enough that organisms can harvest more than they pay
- Harvest yield should provide sufficient energy for reproduction
- Initial energy should give organisms time to execute their first harvest
Reaper Configuration {#reaper-configuration}¶
Natural selection requires the reaper to remove organisms, creating evolutionary pressure.
Essential Settings:
- MIN_POPULATION_FOR_REAP
: Minimum population before reaping starts (default: 50)
- REAP_CHANCE
: Probability of random death per cycle (default: 0.01)
- AGE_THRESHOLD_MULTIPLIER
: Age-based death threshold (default: 3.0)
- ERROR_THRESHOLD_MULTIPLIER
: Error-based death threshold (default: 2.0)
Evolution Goals:
- Growth Phase: Set REAP_CHANCE=0.0
to allow population growth
- Selection Phase: Enable reaping with REAP_CHANCE=0.01
for natural selection
- Stable Evolution: Balance birth/death rates for continuous evolution
Mutation Rate Guidelines {#mutation-rates}¶
Mutation rates must balance genetic diversity with organism viability.
Recommended Settings:
- COPY_BIT_FLIP_RATE
: 0.01 (1% - higher rate for population growth)
- INSERTION_DELETION_RATE
: 0.005 (0.5% - balanced for evolution)
- BACKGROUND_FLIP_INTERVAL
: 500000 (reduces background noise)
Research-Based Values:
- Tierra used ~0.1% mutation rates for viable evolution
- Higher rates create mostly non-viable offspring
- Lower rates prevent genetic diversity
Diagnostic Procedures {#diagnostic-procedures}¶
Healthy Evolution Indicators:
- Population stable at 20-500 organisms
- Continuous births and deaths (balanced turnover)
- Genetic diversity ratio > 0.5
- Mutation rate between 0.1-1.0%
- Memory occupancy < 10%
Stagnation Warning Signs:
- Population crashes from peak to < 50 organisms
- Zero or very low birth rates
- All organisms have zero energy
- Genetic diversity ratio = 1.0 (no evolution)
- High mutation rates (> 5%) with low viability
Troubleshooting Steps:
1. Energy Starvation: Reduce MEMORY_RENT_PER_BYTE
, increase ENV_HARVEST_YIELD
2. No Selection: Enable reaper with REAP_CHANCE=0.01
, lower threshold multipliers
3. Mutation Catastrophe: Reduce INSERTION_DELETION_RATE
to 0.001
4. Population Crashes: Check energy balance and reduce mutation rates
Core Variables {#core-variables-detailed}¶
Resource Management {#resource-management}¶
Variable | Type | Default | Description |
---|---|---|---|
RESOURCE_PRESET |
str | "auto" | Resource preset: "minimal", "background", "standard", "full", "auto" |
CPU_PERCENT |
float | auto-detected | CPU usage limit (0-100) |
MEMORY_MB |
int | auto-detected | Memory limit in MB |
DISK_MB |
int | auto-detected | Disk usage limit in MB |
Server Connection {#server-connection}¶
Variable | Type | Default | Description |
---|---|---|---|
SERVER_URL |
str | "http://localhost:8080" | URL of the server to connect to |
WORKER_ID |
str | auto-generated | Custom worker identifier (optional, machine-based ID if not provided) |
POLL_INTERVAL |
float | auto-detected | Polling interval for work requests |
HEARTBEAT_INTERVAL |
float | auto-detected | Heartbeat interval in seconds |
Batching Configuration {#batching-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
BATCH_SIZE |
int | auto-detected | Number of work cycles per batch |
MIN_BATCH_SIZE |
int | auto-detected | Minimum batch size |
MAX_BATCH_SIZE |
int | auto-detected | Maximum batch size |
TARGET_INTERVAL_SECONDS |
int | auto-detected | Target interval for batch processing |
Adaptive batching is always enabled and no longer controlled by ADAPTIVE_BATCHING
; workers ignore the variable if present.
Standard Variables {#standard-variables-detailed}¶
Soup (Memory) Configuration {#soup-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
SOUP_SIZE |
int | 5000000 | Total size of the organism memory soup in bytes (5MB default) |
MAX_OCCUPANCY_RATIO |
float | 0.7 | Maximum allowed memory occupancy ratio (0.0-1.0) |
Scheduler Configuration {#scheduler-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
SLICER_POWER |
float | 1.0 | Power parameter for CPU time slicing algorithm |
BASE_SLICE |
int | 5 | Base number of instructions per time slice |
REPEAT_SLICES |
int | - | Optional repeat slices for batching operations |
Mutation Configuration {#mutation-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
COPY_BIT_FLIP_RATE |
float | 0.005 | Rate of bit flips during genome copying (~1/200 bits) |
BACKGROUND_FLIP_INTERVAL |
int | 200000 | Interval for background bit flips (~200K instructions) |
INSERTION_DELETION_RATE |
float | 0.14 | Rate of insertion/deletion mutations (~1/7 operations) |
MAX_MAL_MULT |
int | 6 | Maximum multiplier for MAL (Move and Link) operations |
INDEL_INSERTION_BIAS |
float | 0.6 | Bias toward insertions vs deletions (0.5 = unbiased) |
Reaper (Mortality) Configuration {#reaper-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
ERROR_MOVE_UP |
bool | true | Move organisms up in priority queue on errors |
SUCCESS_MOVE_DOWN |
bool | true | Move organisms down in priority queue on success |
PROTECT_CURRENT_CALLER |
bool | true | Protect currently executing organism from reaping |
AGE_ERROR_INTERVAL |
int | 5000 | Interval for age-based error tracking |
AGE_THRESHOLD_MULTIPLIER |
float | 2.0 | Multiplier for age-based reaping threshold |
ERROR_THRESHOLD_MULTIPLIER |
float | 4.0 | Multiplier for error-based reaping threshold |
MIN_POPULATION_FOR_REAP |
int | 5 | Minimum population before reaping is allowed |
MEMORY_REAP_THRESHOLD |
float | 0.75 | Memory usage threshold for triggering reaping |
REPOPULATION_THRESHOLD |
int | 5 | Population threshold to start repopulation |
REPOPULATION_STOP_THRESHOLD |
int | 50 | Population threshold to stop repopulation |
REPOPULATION_BATCH |
int | 5 | Number of organisms to spawn per repopulation batch |
STAGNATION_SPAWN_INTERVAL |
int | 30000 | Interval for spawning during stagnation |
STAGNATION_SPAWN_COUNT |
int | 2 | Number of organisms to spawn during stagnation |
REAP_CHANCE |
float | 0.5 | Probability of reaping an eligible organism |
REPRO_TIMEOUT_STEPS |
int | 20000 | Timeout steps for reproduction operations |
Environment Configuration {#environment-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
ENV_LENGTH |
int | 4096 | Length of the environmental resource field |
ENV_REGEN_INTERVAL |
int | 3000 | Interval for resource regeneration |
ENV_REGEN_AMOUNT |
int | 10 | Amount of resources regenerated per interval |
ENV_SIGNAL_DECAY_INTERVAL |
int | 2000 | Interval for signal decay |
ENV_SIGNAL_DECAY_FACTOR |
float | 0.5 | Factor for signal decay (0.0-1.0) |
ENV_HARVEST_YIELD |
int | 10 | Yield from harvesting resources |
ENV_MAX_RESOURCE |
int | 50 | Maximum resource capacity |
ENV_TASK_REWARD |
int | 60 | Reward for completing tasks |
ENV_STORAGE_SLOTS |
int | 256 | Number of storage slots available (Advanced) |
ENV_ENABLE_GRADIENTS |
bool | true | Enable resource gradients |
ENV_GRADIENT_TYPE |
str | "hotspot" | Type of gradient ("sine", "linear", "hotspot") (Advanced) |
ENV_GRADIENT_AMPLITUDE |
float | 0.6 | Amplitude of gradient variation (0.0-1.0) |
ENV_HOTSPOT_COUNT |
int | 5 | Number of resource hotspots |
ENV_HOTSPOT_SIZE |
int | 80 | Size of each hotspot |
ENV_GRADIENT_PERIOD |
int | 1000 | Period for moving gradients (Advanced) |
Energy Configuration {#energy-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
ENERGY_INITIAL |
int | 200 | Initial energy for new organisms |
ENERGY_MAX |
int | 400 | Maximum energy capacity |
CPU_COST_PER_INSTRUCTION |
float | 0.04 | Energy cost per CPU instruction |
MEMORY_RENT_PER_BYTE |
float | 0.0025 | Energy cost per byte of memory |
HARVEST_MULTIPLIER |
float | 1.2 | Multiplier for harvest efficiency |
TASK_BONUS |
int | 60 | Energy bonus for completing tasks |
CHILD_ENERGY_REQUIREMENT |
int | 25 | Minimum energy required for reproduction |
PRIORITY_BOOST_DURATION |
int | 5 | Steps of CPU priority boost after task completion |
Evolution Configuration {#evolution-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
SEED_BANK_SIZE |
int | 2000 | Size of the evolutionary seed bank |
Ancestor Configuration {#ancestor-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
ANCESTOR_SIZE_LIMIT |
int | 200 | Maximum size for ancestor organisms |
ANCESTOR_LOAD_ADDRESS |
int | 0 | Memory address to load ancestors (Advanced) |
Logging Configuration {#logging-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
LOG_INTERVAL_SLICES |
int | 10000 | Log every N slices |
LOG_JSONL_PATH |
str | "{data_dir}/checkpoints/experiment.jsonl" | Path for JSONL log output (configurable via DATA_BASE_DIR) |
CONSOLE_SUMMARY |
bool | true | Enable console summary output (Advanced) |
Checkpointing Configuration {#checkpointing-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
CHECKPOINT_ENABLED |
bool | true | Enable checkpointing |
CHECKPOINT_DIR |
str | "{data_dir}/checkpoints" | Directory for checkpoint files (configurable via DATA_BASE_DIR) |
CHECKPOINT_CADENCE_SECONDS |
int | 120 | Checkpoint interval in seconds |
CHECKPOINT_KEEP_LAST_N |
int | 10 | Number of checkpoints to retain (Advanced) |
Global Simulation Parameters {#global-simulation-parameters}¶
Variable | Type | Default | Description |
---|---|---|---|
SEED |
int | - | Random seed for reproducible runs |
MAX_STEPS |
int | - | Maximum simulation steps |
CPU_THROTTLE_DELAY |
float | 0.00001 | Delay between simulation steps (seconds) |
Data Management Configuration {#data-management-configuration}¶
ByteBiota uses a centralized data management system that allows you to customize where all data files are stored. This is particularly useful for production deployments, testing environments, or when you need to store data on specific storage devices.
Data Directory Configuration {#data-directory-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
DATA_BASE_DIR |
str | "data" | Base directory for all data files (overrides all data paths) |
Data Directory Structure {#data-directory-structure}¶
When DATA_BASE_DIR
is set, the following directory structure is automatically created:
{DATA_BASE_DIR}/
βββ logs/ # Server and worker log files
βββ checkpoints/ # Simulation checkpoint files
β βββ server/ # Server checkpoint files
β βββ worker/ # Worker checkpoint files
βββ cache/ # Offline cache and temporary files
βββ reports/ # Tuning reports and analysis
βββ test-results/ # Test execution results
Data Management Features {#data-management-features}¶
- Centralized Configuration: Set
DATA_BASE_DIR
once to configure all data paths - Automatic Directory Creation: All required directories are created automatically
- Environment Override: Individual paths can still be overridden with specific environment variables
- Production Ready: Perfect for containerized deployments and custom storage mounts
Data Management Examples {#data-management-examples}¶
Example 1: Custom Data Directory¶
# Store all data in /var/lib/bytebiota
export DATA_BASE_DIR="/var/lib/bytebiota"
# This automatically sets:
# - Logs: /var/lib/bytebiota/logs/
# - Checkpoints: /var/lib/bytebiota/checkpoints/
# - Cache: /var/lib/bytebiota/cache/
# - Reports: /var/lib/bytebiota/reports/
Example 2: Development Environment¶
# Use a development-specific data directory
export DATA_BASE_DIR="./dev-data"
# All components will use ./dev-data/ subdirectories
Example 3: Production with Custom Storage¶
# Mount custom storage and use it for all data
export DATA_BASE_DIR="/mnt/bytebiota-storage"
# Perfect for high-performance storage or network mounts
Distributed System Configuration {#distributed-system-configuration}¶
Server Configuration {#server-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
SERVER_HOST |
str | "0.0.0.0" | Server host address |
SERVER_PORT |
int | 8080 | Server port number |
MAX_WORKERS |
int | 100 | Maximum number of workers |
WORKER_TIMEOUT |
int | - | Worker timeout in seconds |
HEARTBEAT_INTERVAL |
int | - | Heartbeat interval in seconds |
CHECKPOINT_INTERVAL |
int | 300 | Server checkpoint interval |
Web UI Configuration {#web-ui-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
ENABLE_WEB_UI |
bool | true | Enable web user interface |
STATIC_DIR |
str | - | Directory for static web assets (Advanced) |
TEMPLATE_DIR |
str | - | Directory for web templates (Advanced) |
LOG_LEVEL |
str | - | Logging level (DEBUG, INFO, WARNING, ERROR) |
WebSocket Configuration {#websocket-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
WEBSOCKET_ENABLED |
bool | true | Enable WebSocket communication |
WEBSOCKET_MAX_MESSAGE_SIZE |
int | - | Maximum WebSocket message size |
WEBSOCKET_COMPRESSION_THRESHOLD |
int | - | Compression threshold for WebSocket messages |
Worker Configuration {#worker-configuration}¶
Worker Identity {#worker-identity}¶
Variable | Type | Default | Description |
---|---|---|---|
WORKER_ID |
str | - | Custom worker identifier (optional, machine-based ID if not provided) |
Server Connection {#server-connection-worker}¶
Variable | Type | Default | Description |
---|---|---|---|
SERVER_URL |
str | "http://localhost:8080" | URL of the server to connect to |
POLL_INTERVAL |
float | 1.0 | Polling interval for work requests |
HEARTBEAT_INTERVAL |
float | 10.0 | Heartbeat interval in seconds |
WORK_CYCLE_DELAY |
float | - | Delay between work cycles |
Resource Management {#resource-management-worker}¶
Variable | Type | Default | Description |
---|---|---|---|
RESOURCE_PRESET |
str | "standard" | Resource preset ("background", "standard", "full") |
CPU_PERCENT |
float | - | CPU usage percentage limit |
MEMORY_MB |
int | - | Memory limit in megabytes |
DISK_MB |
int | - | Disk usage limit in megabytes |
THROTTLE_SLEEP_MS |
float | - | Sleep time for throttling in milliseconds |
DISABLE_THROTTLE |
bool | false | Disable resource throttling |
Local Simulation {#local-simulation}¶
Variable | Type | Default | Description |
---|---|---|---|
LOCAL_SOUP_SIZE |
int | - | Size of local simulation soup |
CHECKPOINT_DIR |
str | "{data_dir}/checkpoints/worker" | Directory for worker checkpoints (configurable via DATA_BASE_DIR) |
Execution Settings {#execution-settings}¶
Variable | Type | Default | Description |
---|---|---|---|
MAX_WORK_CYCLES |
int | - | Maximum work cycles before restart |
ERROR_THRESHOLD |
int | - | Error threshold before worker restart |
Worker WebSocket Configuration {#worker-websocket-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
WEBSOCKET_URL |
str | - | WebSocket URL for worker communication |
OFFLINE_CACHE_MAX_MB |
int | - | Maximum offline cache size in MB |
ADAPTIVE_HEARTBEAT |
bool | false | Enable adaptive heartbeat timing |
WEBSOCKET_RECONNECT_MAX_ATTEMPTS |
int | - | Maximum WebSocket reconnection attempts |
WEBSOCKET_MAX_MESSAGE_SIZE |
int | - | Maximum WebSocket message size |
Worker Batching Configuration {#worker-batching-configuration}¶
Variable | Type | Default | Description |
---|---|---|---|
BATCH_SIZE |
int | 8 | Number of work cycles per batch |
CONFIG_SYNC_INTERVAL |
int | 50 | Configuration sync interval |
MIN_BATCH_SIZE |
int | 8 | Minimum batch size |
MAX_BATCH_SIZE |
int | 200 | Maximum batch size |
TARGET_INTERVAL_SECONDS |
int | 300 | Target interval for batch processing |
WORK_RATE_THRESHOLD |
int | 200 | Work rate threshold for batching |
ADJUSTMENT_FACTOR |
float | 0.15 | Batching adjustment factor |
BULK_ASSIGNMENT |
bool | true | Enable bulk work assignment |
BULK_POLL_INTERVAL |
int | 300 | Bulk assignment polling interval |
Adaptive batching is always enabled for workers; the legacy ADAPTIVE_BATCHING
variable is ignored.
Tuning System Optimization {#tuning-system-optimization}¶
The hybrid tuning system has been optimized to prevent excessive tuning activity:
- Event Fast-Lane Bypass: Event results (births, deaths, seed submissions) with
step_count=0
do not trigger tuning assessments, preventing tuning system overload during high-activity periods. - Step-Based Triggering: Tuning cycles only run when results contain actual simulation steps (
step_count > 0
), ensuring tuning assessments align with simulation progress. - Batch Size Optimization: Default
BATCH_SIZE
increased from 1 to 8 to reduce submission frequency while maintaining responsiveness.
This optimization reduces tuning activity from every 20 seconds to the expected 5-10 minute intervals while maintaining real-time responsiveness for critical events.
Development and Testing {#development-and-testing}¶
Python Environment {#python-environment}¶
Variable | Type | Default | Description |
---|---|---|---|
PYTHONPATH |
str | - | Python path for module resolution |
Testing and Monitoring {#testing-and-monitoring}¶
Variable | Type | Default | Description |
---|---|---|---|
BYTEBIOta_SERVER_URL |
str | "http://localhost:8080" | Server URL for testing and monitoring |
Production Configuration {#production-configuration}¶
Systemd Service Environment {#systemd-service-environment}¶
The following environment variables are commonly set in production systemd services:
Server Service:
- PYTHONPATH=/opt/bytebiota/src
- SERVER_HOST=0.0.0.0
- SERVER_PORT=8080
- MAX_WORKERS=100
- SEED_BANK_SIZE=2000
- CHECKPOINT_INTERVAL=300
Worker Service:
- PYTHONPATH=/opt/bytebiota/src
- SERVER_URL=http://localhost:8080
- RESOURCE_PRESET=standard
- POLL_INTERVAL=1.0
- HEARTBEAT_INTERVAL=10.0
Usage Examples {#usage-examples}¶
Example 1: Minimal Desktop Worker (Auto-Detection)¶
# Use auto-detection for optimal settings
python -m bytebiota worker --preset auto
# Output will show:
# Auto-detecting optimal resource configuration...
# Detected: 8 CPU cores, 8192MB memory
# Recommended preset: standard
# Optimal settings: CPU=100%, Batch size=4
# Using auto-detected optimal configuration
Example 2: Dedicated Server Worker (Explicit Limits)¶
# Explicitly set resource limits for dedicated server
python -m bytebiota worker \
--server-url http://server:8080 \
--cpu-percent 50 \
--memory-mb 4096 \
--batch-size 10
Example 3: Background Worker (Preset)¶
# Use background preset for minimal resource usage
python -m bytebiota worker \
--preset background \
--server-url http://server:8080
Example 4: Full Power Worker¶
# Use full preset or explicit 100% CPU
python -m bytebiota worker \
--preset full \
--server-url http://server:8080
# Or explicitly set 100% CPU
python -m bytebiota worker \
--cpu-percent 100 \
--memory-mb 8192 \
--server-url http://server:8080
Environment Variable Examples¶
# Basic local development
export SOUP_SIZE=100000
export MAX_OCCUPANCY_RATIO=0.8
export COPY_BIT_FLIP_RATE=0.001
python -m bytebiota run
# Distributed deployment
export SERVER_HOST=0.0.0.0
export SERVER_PORT=8080
export MAX_WORKERS=50
export ENABLE_WEB_UI=true
python -m bytebiota server
# Worker with custom settings
export WORKER_ID=worker-001
export SERVER_URL=http://server:8080
export RESOURCE_PRESET=background
export CPU_PERCENT=25
python -m bytebiota worker
Systemd Service Files¶
# /etc/systemd/system/bytebiota-server.service
[Unit]
Description=ByteBiota Distributed Server
After=network.target
[Service]
Type=simple
User=bytebiota
Group=bytebiota
WorkingDirectory=/opt/bytebiota
Environment=PYTHONPATH=/opt/bytebiota/src
EnvironmentFile=/opt/bytebiota/.env
# Pass env vars explicitly to override CLI defaults
ExecStart=/opt/bytebiota/.venv/bin/python -m bytebiota server --host ${SERVER_HOST} --port ${SERVER_PORT} --no-reload
Restart=always
[Install]
WantedBy=multi-user.target
# /etc/systemd/system/bytebiota-worker@.service
[Unit]
Description=ByteBiota Worker %i
After=network.target
[Service]
Type=simple
User=bytebiota
Group=bytebiota
WorkingDirectory=/opt/bytebiota
Environment=PYTHONPATH=/opt/bytebiota/src
EnvironmentFile=/opt/bytebiota/.env
# Override worker ID for this instance
Environment=WORKER_ID=worker-%i
ExecStart=/opt/bytebiota/.venv/bin/python -m bytebiota worker
Restart=always
[Install]
WantedBy=multi-user.target
Configuration Precedence {#configuration-precedence}¶
Environment variables are loaded in the following order (later values override earlier ones):
- System environment variables
.env
file in current directory.env
file in parent directories (searched upward)- Systemd/supervisor environment settings
- Command-line arguments
Worker Environment Loading {#worker-environment-loading}¶
Both server and worker components now support automatic .env
file loading using python-dotenv
. The worker searches for .env
files in the same manner as the server:
- Current working directory (where the command is run)
- Parent directories (searched upward from the code file location)
- Stops at the first
.env
file found
Important Notes:
- .env
values only fill missing environment variables (existing env vars take precedence)
- Both Config.from_env()
(server) and WorkerConfig.from_env()
(worker) load .env
files
- Use load_dotenv(override=False)
to respect existing environment variables
CLI Argument Precedence {#cli-argument-precedence}¶
Server CLI Behavior:
The python -m bytebiota server
command has default values that override environment variables:
- --host
defaults to 0.0.0.0
and overrides SERVER_HOST
from .env
- --port
defaults to 8080
and overrides SERVER_PORT
from .env
Solution: Pass environment variables explicitly to CLI:
python -m bytebiota server --host ${SERVER_HOST} --port ${SERVER_PORT}
Worker CLI Behavior:
The python -m bytebiota worker
command respects environment variables:
- --worker-id
has no default, so .env
values are used
- --server-url
defaults to http://localhost:8080
but only overrides if explicitly provided
Best Practice: Use .env
files for worker configuration, pass explicit values for server CLI.
Validation {#validation}¶
All configuration values are validated at startup. Invalid values will cause the system to exit with an error message indicating the problematic parameter.
Troubleshooting {#troubleshooting}¶
.env File Not Loading¶
Symptoms:
- Environment variables from .env
file are not being used
- Worker shows auto-generated ID instead of WORKER_ID
from .env
- Server binds to 0.0.0.0
instead of 127.0.0.1
from .env
Solutions:
-
Check file location and permissions:
bash # Ensure .env is in the correct location ls -la .env # Should show: -rw-r--r-- 1 user group size date .env
-
Verify .env file format:
bash # Check for clean KEY=value format (no spaces around =) cat .env # Should show: WORKER_ID=geckom-macbook # NOT: WORKER_ID = geckom-macbook
-
Test environment loading:
bash # Test if .env is loaded python -c " from src.bytebiota.worker.config import WorkerConfig config = WorkerConfig.from_env() print('Worker ID:', config.worker_id) "
-
Check working directory:
bash # Ensure you're running from the correct directory pwd # Should be the directory containing .env
-
For systemd services:
bash # Ensure WorkingDirectory points to .env location # Use EnvironmentFile=/path/to/.env in service file # Pass explicit values for server: --host ${SERVER_HOST} --port ${SERVER_PORT}