Files
Echoion/.opencode/plans/robustness_plan.md
T

21 KiB

Echoion Robustness Improvement Plan

Executive Summary

This plan addresses robustness for 100+ concurrent users on 4core/8GB hardware while maintaining the TeamSpeak plugin architecture with weekly hot-reload capability.

Key Architectural Principle: Plugin and Core are completely decoupled. Core manages its own state serialization/deserialization internally. Plugin only handles opaque state blobs.

Dependencies: Uses only existing dependencies (glaze, Boost, TBB, etc.). No new dependencies required.

Current Pain Points

1. Connection Handling (Critical)

  • Issue: Thread-per-client model creates unlimited threads (RpcServer.cpp:167-196)
  • Risk: Resource exhaustion with 100+ users
  • Impact: System instability, crashes

2. No Resource Limits

  • Issue: No memory/CPU limits, unbounded queue growth
  • Risk: OOM kills, audio dropouts
  • Impact: Service degradation for all users

3. Missing Circuit Breakers

  • Issue: yt-dlp failures cascade (no failure isolation)
  • Risk: Repeated failed requests consume resources
  • Impact: Bot becomes unresponsive

4. Race Conditions

  • Issue: Queue modifications lack proper synchronization
  • Risk: Data corruption, crashes
  • Impact: Inconsistent state

5. No Health Monitoring

  • Issue: No self-diagnostics or automatic recovery
  • Risk: Silent failures accumulate
  • Impact: Extended downtime

Decoupled State Management Architecture

The key insight: Plugin should never know what state Core needs to save. Core handles all serialization internally using versioned formats.

┌─────────────────────────────────────────────────────────────────────┐
│                    TeamSpeak Client                                  │
│  ┌───────────────────────────────────────────────────────────────┐  │
│  │              EchoionPlugin (.ts plugin)                        │  │
│  │                                                                │  │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐ │  │
│  │  │   Plugin     │  │   Health     │  │   StateManager       │ │  │
│  │  │  Interface   │  │   Monitor    │  │   (Opaque Blob)      │ │  │
│  │  └──────────────┘  └──────────────┘  └──────────────────────┘ │  │
│  │                                                                │  │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐ │  │
│  │  │  CoreLoader  │  │  Connection  │  │   Watchdog           │ │  │
│  │  │ (Hot Reload) │  │    Pool      │  │   (Heartbeat)        │ │  │
│  │  └──────────────┘  └──────────────┘  └──────────────────────┘ │  │
│  │                                                                │  │
│  │  Plugin ONLY knows:                                            │  │
│  │  - Core exports: saveState() -> opaque blob                    │  │
│  │  - Core exports: restoreState(blob) -> success/failure         │  │
│  │  - Plugin stores blob temporarily, passes it back              │  │
│  │  - Plugin NEVER parses or inspects blob contents               │  │
│  │                                                                │  │
│  └───────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────┘
                              │
                              │ dylib::library (hot reloadable)
                              │ 
                              ▼
┌─────────────────────────────────────────────────────────────────────┐
│                    EchoionCore (.ts library)                         │
│  ┌───────────────────────────────────────────────────────────────┐  │
│  │                                                                │  │
│  │  Core Internally Manages:                                      │  │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐ │  │
│  │  │ StateVersion │  │  Migration   │  │   StateSerializer    │ │  │
│  │  │   (v1, v2)   │  │   Engine     │  │   (glaze JSON)       │ │  │
│  │  └──────────────┘  └──────────────┘  └──────────────────────┘ │  │
│  │                                                                │  │
│  │  State Format can change without Plugin rebuild:               │  │
│  │  - Old Core saves state v1                                     │  │
│  │  - New Core loads state v1, migrates to v2 internally          │  │
│  │  - Plugin just passes the blob through                         │  │
│  │                                                                │  │
│  └───────────────────────────────────────────────────────────────┘  │
│                                                                      │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐               │
│  │   Core       │  │   RPC        │  │   Resource   │               │
│  │   (Main)     │◄─┤   Server     │  │   Manager    │               │
│  └──────────────┘  └──────────────┘  └──────────────┘               │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐               │
│  │ MusicManager │  │  YtDlpMgr    │  │   Session    │               │
│  │              │  │ (Circuit     │  │   Manager    │               │
│  │              │  │  Breaker)    │  │              │               │
│  └──────────────┘  └──────────────┘  └──────────────┘               │
└─────────────────────────────────────────────────────────────────────┘

Decoupled State Management Design

Core Interface (Stable API)

// EchoionApi - Stable interface, never changes
class ICoreInterface {
public:
    // State management - opaque to Plugin
    virtual Api::SerializedState saveState() = 0;
    virtual Api::Result<void> restoreState(const Api::SerializedState& state) = 0;
    
    // Version info for compatibility
    virtual uint32_t getStateFormatVersion() = 0;
    virtual bool canRestoreStateVersion(uint32_t version) = 0;
};

// SerializedState is just an opaque blob
namespace Api {
    struct SerializedState {
        std::vector<uint8_t> data;  // Plugin never inspects this
        uint32_t version;           // Format version for logging only
        std::string timestamp;      // ISO 8601 for debugging
    };
}

Core Internal State Management (Can Change Freely)

Uses glaze (already available) for JSON serialization:

// EchoionCore - Internal implementation, can change anytime
class Core : public ICoreInterface {
private:
    // Current state format version
    static constexpr uint32_t CURRENT_STATE_VERSION = 2;
    
    // Internal state structure - can change without affecting Plugin
    struct StateV2 {
        std::vector<QueueEntry> queue;
        std::optional<PlaybackState> currentTrack;
        float volume;
        // ... new fields can be added anytime
    };
    
    // Migration support for backward compatibility
    class StateMigration {
    public:
        static StateV2 migrateFromV1(const glz::json_t& v1Data);
        static StateV2 migrateFromV0(const glz::json_t& v0Data);
    };
    
public:
    Api::SerializedState saveState() override {
        StateV2 currentState = captureCurrentState();
        
        // Serialize to JSON using glaze (already available)
        std::string jsonState;
        auto ec = glz::write_json(currentState, jsonState);
        if (ec) {
            // Handle error
            return Api::SerializedState{};
        }
        
        // Convert to binary blob
        std::vector<uint8_t> data(jsonState.begin(), jsonState.end());
        
        return Api::SerializedState{
            .data = std::move(data),
            .version = CURRENT_STATE_VERSION,
            .timestamp = getCurrentTimestamp()
        };
    }
    
    Api::Result<void> restoreState(const Api::SerializedState& state) override {
        // Convert blob back to string
        std::string jsonStr(state.data.begin(), state.data.end());
        
        // Parse version from JSON using glaze
        uint32_t dataVersion = extractVersion(jsonStr);
        
        // Migrate if needed (all handled internally)
        if (dataVersion == CURRENT_STATE_VERSION) {
            // Direct parse
            StateV2 restoredState;
            auto ec = glz::read_json(restoredState, jsonStr);
            if (ec) {
                return std::unexpected(Api::Error(
                    Api::ErrorCode::ParseError,
                    "Failed to parse state"
                ));
            }
            applyState(restoredState);
        } else if (dataVersion == 1) {
            // Parse as V1, then migrate
            StateV1 v1State;
            auto ec = glz::read_json(v1State, jsonStr);
            if (ec) {
                return std::unexpected(Api::Error(
                    Api::ErrorCode::ParseError,
                    "Failed to parse V1 state"
                ));
            }
            StateV2 migrated = StateMigration::migrateFromV1(v1State);
            applyState(migrated);
        } else {
            return std::unexpected(Api::Error(
                Api::ErrorCode::IncompatibleVersion,
                std::format("Cannot restore state version {} (current: {})", 
                           dataVersion, CURRENT_STATE_VERSION)
            ));
        }
        
        return {};
    }
};

Plugin State Management (Simple Pass-Through)

// EchoionPlugin - Never touches state internals
class CoreLoader {
public:
    Api::Result<void> hotReload(const std::filesystem::path& newLibraryPath) {
        // 1. Ask Core to save its state (opaque blob)
        Api::SerializedState state;
        if (core_) {
            state = core_->saveState();
            logInfo(std::format("Saved state: version={}, size={} bytes",
                               state.version, state.data.size()));
        }
        
        // 2. Unload old Core
        auto unloadResult = unloadLibraryInternal();
        if (!unloadResult) return unloadResult;
        
        // 3. Load new Core
        auto loadResult = loadLibraryInternal(newLibraryPath);
        if (!loadResult) return loadResult;
        
        // 4. Ask new Core to restore state (it handles migration internally)
        if (!state.data.empty()) {
            auto coreVersion = core_->getStateFormatVersion();
            auto stateVersion = state.version;
            
            if (core_->canRestoreStateVersion(stateVersion)) {
                auto restoreResult = core_->restoreState(state);
                if (!restoreResult) {
                    logError(std::format("Failed to restore state v{} to Core v{}",
                                        stateVersion, coreVersion));
                    // Continue with empty state - graceful degradation
                } else {
                    logInfo("State restored successfully");
                }
            } else {
                logWarning(std::format("Cannot restore state v{} in Core v{}",
                                      stateVersion, coreVersion));
                // Continue with empty state
            }
        }
        
        return {};
    }
};

State Format Evolution Example

// Week 1: StateV1
struct StateV1 {
    std::vector<QueueEntry> queue;
    float volume;
};

// Week 2: StateV2 (added new field)
struct StateV2 {
    std::vector<QueueEntry> queue;
    float volume;
    bool shuffleMode;  // NEW FIELD
    
    static V2 migrateFromV1(const V1& v1) {
        return V2{
            .queue = v1.queue,
            .volume = v1.volume,
            .shuffleMode = false  // Default for migrated states
        };
    }
};

// Week 3: StateV3 (changed structure)
struct StateV3 {
    struct Playlist {
        std::vector<QueueEntry> tracks;
        uint32_t currentIndex;
    };
    
    Playlist playlist;  // Changed from flat queue
    PlaybackSettings settings;  // Grouped settings
    
    static V3 migrateFromV2(const V2& v2) {
        return V3{
            .playlist = {.tracks = v2.queue, .currentIndex = 0},
            .settings = {.volume = v2.volume, .shuffle = v2.shuffleMode}
        };
    }
};

// Plugin never needs to know about these changes!

Implementation Phases

Phase 0: Decoupled State Management Foundation (Week 0)

Goal: Establish the decoupled architecture before other improvements

New Components:

  1. StateSerializer.hpp/cpp (Core) - Versioned state serialization using glaze
  2. StateMigration.hpp/cpp (Core) - Migration between versions
  3. Update ICoreInterface.hpp (Api) - Add state management methods
  4. Refactor Core.cpp - Implement internal state management
  5. Refactor CoreLoader.cpp - Use opaque state blobs

Key Design Decisions:

  • State format uses glaze JSON (already available, high performance)
  • Version stored in JSON for easy inspection
  • Migration chain: V0 -> V1 -> V2 -> V3 (each version only knows previous)
  • Graceful degradation: if migration fails, start fresh (don't crash)

Phase 1: Connection Pool & Rate Limiting (Week 1)

Goal: Handle 100+ concurrent RPC connections safely

Components:

  1. ConnectionPool.hpp/cpp - Fixed-size worker thread pool (16 workers)
  2. RateLimiter.hpp/cpp - Token bucket per client IP (30 req/min, burst 10)
  3. Update RpcServer.cpp - Integrate connection pool

Dependencies: Uses Boost.Asio (already available)

Phase 2: Resource Management (Week 1-2)

Goal: Prevent resource exhaustion on 4core/8GB

Components:

  1. ResourceMonitor.hpp/cpp - Track memory/CPU usage
  2. Update MusicManager.cpp - Queue limits (500 tracks), memory caps
  3. Update YtDlpManager.cpp - Limit concurrent operations (4 max)

Dependencies: Uses standard library + TBB (already available)

Phase 3: Circuit Breakers & Fault Isolation (Week 2)

Goal: Prevent cascading failures

Components:

  1. CircuitBreaker.hpp/cpp - Generic circuit breaker pattern
  2. Update YtDlpManager.cpp - Add circuit breaker (5 failures = 60s cooldown)
  3. Update NetworkClient.cpp - Circuit breaker for HTTP calls

Dependencies: Uses standard library only (chrono, atomic)

Phase 4: Session Management (Week 2-3)

Goal: Support 100+ users with proper session handling

Components:

  1. SessionManager.hpp/cpp - Track authenticated sessions (max 150)
  2. Update RpcServer.cpp - Integrate session management
  3. Sessions automatically included in Core's state blob (no Plugin changes!)

Dependencies: Uses glaze (already available) + standard library

Phase 5: Health Monitoring & Self-Healing (Week 3)

Goal: Automatic recovery from failures

Components:

  1. HealthMonitor.hpp/cpp - System health checks (every 5s)
  2. Watchdog.hpp/cpp - Detect hangs (15s timeout)
  3. Update Plugin.cpp - Integrate health monitoring

Dependencies: Uses standard library + Boost.Asio (already available)

Phase 6: Enhanced yt-dlp Management (Week 3-4)

Goal: Reliable auto-updates with fallback

Components:

  1. Update YtDlpManager.cpp - Background updates, atomic swap
  2. UpdateScheduler.hpp/cpp - Weekly update scheduling (configurable window)

Dependencies: Uses standard library only

Configuration Summary

{
  "robustness": {
    "stateManagement": {
      "format": "glaze_json",
      "maxStateSizeMB": 10,
      "migration": {
        "maxVersionsBackward": 5,
        "gracefulDegradation": true
      }
    },
    "rpc": {
      "maxConnections": 150,
      "workerThreads": 16,
      "rateLimitRequestsPerMinute": 30,
      "rateLimitBurst": 10,
      "connectionTimeoutMs": 30000,
      "sessionTimeoutMs": 3600000
    },
    "resourceLimits": {
      "maxQueueSize": 500,
      "maxMemoryMB": 1024,
      "maxYtDlpConcurrent": 4,
      "maxAudioBufferMB": 256,
      "enableMemoryPressureHandling": true,
      "memoryPressureThresholdMB": 768
    },
    "circuitBreaker": {
      "ytDlpFailureThreshold": 5,
      "ytDlpResetTimeoutMs": 60000,
      "networkFailureThreshold": 3,
      "networkResetTimeoutMs": 30000
    },
    "healthMonitor": {
      "checkIntervalMs": 5000,
      "unhealthyThresholdMs": 30000,
      "enableAutoRecovery": true,
      "maxConsecutiveRecoveries": 3
    },
    "watchdog": {
      "heartbeatIntervalMs": 5000,
      "timeoutMs": 15000,
      "enableAutoReload": true
    },
    "ytDlp": {
      "autoUpdate": true,
      "updateIntervalDays": 7,
      "updateTimeWindow": "02:00-04:00",
      "enableFallbackMirrors": true,
      "requestTimeoutMs": 30000,
      "enableRequestDeduplication": true
    }
  }
}

Dependencies Used

All dependencies are already in your project:

  1. glaze - JSON serialization for state management
  2. Boost.Asio/Beast - Connection pool, RPC server
  3. Boost.UUID - Session IDs
  4. TBB - Parallel algorithms for resource monitoring
  5. standard library - Circuit breakers, rate limiters, health monitoring

No new dependencies required!

Benefits of Decoupled State Management

  1. Plugin Stability: Plugin code never changes when Core state format changes
  2. Rapid Iteration: Modify Core state structure without rebuilding Plugin
  3. Backward Compatibility: Old states automatically migrate to new format
  4. Forward Compatibility: Can detect if state is from future version
  5. Debugging: State blobs can be saved to disk and inspected manually (JSON)
  6. Testing: Easy to create test states for specific scenarios
  7. Performance: Uses glaze (high-performance JSON library you already have)

Hot-Reload Flow with Decoupled State

1. Core V1 running, users connected, music playing
         │
         ▼
2. Developer builds Core V2 (new state format)
         │
         ▼
3. File watcher detects new .ts library
         │
         ▼
4. Plugin asks Core V1: saveState()
   Core V1 serializes internal state to blob (format V1)
         │
         ▼
5. Plugin unloads Core V1, loads Core V2
         │
         ▼
6. Plugin asks Core V2: restoreState(blob V1)
   Core V2 internally migrates V1 -> V2
   Users stay connected, queue preserved
         │
         ▼
7. Core V2 running with migrated state
   Zero downtime, zero Plugin changes

Success Metrics

  • Uptime: >99.9%
  • Concurrent Users: 100+ without degradation
  • Memory: Stable <1GB under load
  • Recovery Time: <5s from failure
  • Hot-Reload: Zero user impact, zero Plugin rebuilds
  • State Migration: 100% success rate for versions within 5 releases

Next Steps

  1. Review this updated plan - Does the decoupled state approach meet your needs?
  2. State format preferences - glaze JSON OK, or prefer binary (using std::vector<uint8_t> with custom format)?
  3. Migration depth - Support 5 versions back, or more/less?
  4. Start implementation - Begin with Phase 0 (state management foundation)?

The decoupled architecture means you can iterate on Core weekly without ever touching Plugin code again, and we're only using dependencies you already have!