/ MIGRATION_PLAN.md
MIGRATION_PLAN.md
   1  # Chainlit & LangGraph Upgrade Migration Plan
   2  
   3  **Project:** chainlit_langgraph
   4  **Current Version:** 0.3.1
   5  **Target Version:** 0.4.0
   6  **Date Created:** 2025-10-27
   7  **Prepared By:** Claude Code
   8  
   9  ---
  10  
  11  ## Executive Summary
  12  
  13  ### Version Upgrades
  14  
  15  | Package | Current | Target | Impact |
  16  |---------|---------|--------|--------|
  17  | **Chainlit** | 1.3.1 | 2.8.3 | 🔴 HIGH - Major breaking changes |
  18  | **LangGraph** | 0.2.45 | 1.0.1 | 🟢 LOW - Backward compatible |
  19  | **LangChain** | 0.3.7 | 0.3.x | 🟢 LOW - Keep current |
  20  | **Python** | 3.10 | 3.10+ | ✅ Compatible |
  21  
  22  ### Key Metrics
  23  
  24  - **Estimated Effort:** 3-5 days (26-33 hours)
  25  - **Risk Level:** Medium-High
  26  - **Code Changes Required:** Minimal (mostly configuration)
  27  - **Data Migration Required:** No (schema compatible)
  28  - **Rollback Difficulty:** Low (git revert + backup restore)
  29  
  30  ### Critical Success Factors
  31  
  32  1. ✅ Configuration file cleanup (`.chainlit/config.toml`)
  33  2. ✅ Comprehensive testing of all 5 workflows
  34  3. ✅ Database backup before upgrade
  35  4. ✅ Authentication flow validation
  36  5. ✅ State persistence verification
  37  
  38  ---
  39  
  40  ## Current System Analysis
  41  
  42  ### Architecture Overview
  43  
  44  ```
  45  ┌─────────────────────────────────────────────────────────────┐
  46  │                     Chainlit Application                     │
  47  │  ┌─────────────┐  ┌──────────────┐  ┌──────────────────┐   │
  48  │  │   Auth      │  │  Workflows   │  │   LLM Factory    │   │
  49  │  │  (Password/ │  │  (5 custom)  │  │  (6 providers)   │   │
  50  │  │   OAuth)    │  └──────────────┘  └──────────────────┘   │
  51  │  └─────────────┘                                             │
  52  │         │                    │                    │           │
  53  │         └────────────────────┴────────────────────┘           │
  54  │                              │                                │
  55  │                      LangGraph Engine                         │
  56  │                    (StateGraph + Tools)                       │
  57  └─────────────────────────────────────────────────────────────┘
  58  59           ┌─────────────────────┼─────────────────────┐
  60           │                     │                     │
  61     ┌─────▼──────┐       ┌─────▼──────┐      ┌──────▼──────┐
  62     │ PostgreSQL │       │   MinIO    │      │  LLM APIs   │
  63     │  (State &  │       │  (Files)   │      │ (Multiple)  │
  64     │   Threads) │       └────────────┘      └─────────────┘
  65     └────────────┘
  66  ```
  67  
  68  ### Dependency Tree
  69  
  70  ```
  71  chainlit-langgraph (0.3.1)
  72  ├── chainlit==1.3.1 ❌ NEEDS UPGRADE
  73  │   ├── sqlalchemy==2.0.36 ✅
  74  │   └── asyncpg==0.29.0 ✅
  75  ├── langgraph==0.2.45 ⚠️ NEEDS UPGRADE
  76  │   ├── langgraph-checkpoint==2.0.2 ✅
  77  │   └── langchain-core==0.3.15 ✅
  78  ├── langchain==0.3.7 ✅
  79  ├── langchain-anthropic==0.2.4 ⚠️ MINOR UPDATE
  80  ├── langchain-openai==0.2.5 ⚠️ MINOR UPDATE
  81  ├── langchain-google-genai==2.0.4 ✅
  82  ├── langchain-google-vertexai==2.0.7 ✅
  83  ├── langchain-groq==0.2.1 ✅
  84  ├── langchain-ollama==0.2.0 ✅
  85  ├── boto3==1.35.41 ✅
  86  ├── alembic==1.13.3 ✅
  87  ├── psycopg2-binary==2.9.9 ✅
  88  └── pypdf==5.0.1 ✅
  89  ```
  90  
  91  ### Critical Usage Patterns
  92  
  93  **Chainlit Decorators (app.py):**
  94  - `@cl.on_chat_start` (Line 164) - Workflow initialization
  95  - `@cl.on_message` (Line 197) - Message handling with streaming
  96  - `@cl.on_chat_end` (Line 52) - State persistence
  97  - `@cl.on_chat_resume` (Line 86) - Session restoration
  98  - `@cl.on_settings_update` (Line 183) - Settings management
  99  - `@cl.set_chat_profiles` (Line 155) - Workflow selection
 100  - `@cl.password_auth_callback` (Line 143) - Authentication
 101  - `@maybe_oauth_callback` (Line 132) - OAuth integration
 102  
 103  **LangGraph Patterns (chat_workflow/workflows/):**
 104  - `StateGraph` with custom state classes
 105  - `graph.compile()` for runnable creation
 106  - `graph.astream_events(state, version="v1")` for streaming
 107  - Custom node implementations with tool routing
 108  - Message history management with `operator.add`
 109  
 110  **Custom Integrations:**
 111  - Multi-provider LLM factory (6 providers)
 112  - Dynamic workflow discovery system
 113  - State serialization for LangChain messages
 114  - MinIO S3-compatible storage
 115  - SQLAlchemy data layer with custom tables
 116  
 117  ---
 118  
 119  ## Breaking Changes Analysis
 120  
 121  ### Chainlit 1.3.1 → 2.8.3
 122  
 123  #### 🔴 CRITICAL: Configuration File Changes
 124  
 125  **Location:** `.chainlit/config.toml`
 126  
 127  **Changes Required:**
 128  
 129  1. **Remove deprecated fields:**
 130     ```toml
 131     # ❌ DELETE THESE LINES
 132     follow_symlink = false  # Line 19 (commented)
 133     custom_font = "..."     # Line 80 (commented)
 134     ```
 135  
 136  2. **Remove `[features.audio]` section (Lines 41-53):**
 137     ```toml
 138     # ❌ DELETE THIS ENTIRE SECTION
 139     [features.audio]
 140         min_decibels = -45
 141         initial_silence_timeout = 3000
 142         silence_timeout = 1500
 143         max_duration = 15000
 144         chunk_duration = 1000
 145         sample_rate = 44100
 146     ```
 147     **Reason:** Audio API completely reworked. Use new callbacks if needed:
 148     - `@cl.on_audio_start`
 149     - `@cl.on_audio_chunk`
 150     - `@cl.on_audio_end`
 151  
 152  3. **Remove `[UI.theme]` section (Lines 90-119):**
 153     ```toml
 154     # ❌ DELETE THIS ENTIRE SECTION
 155     [UI.theme]
 156         default = "dark"
 157     [UI.theme.light]
 158         ...
 159     [UI.theme.dark]
 160         ...
 161     ```
 162     **Reason:** Theme customization moved to separate `theme.json` file.
 163  
 164  4. **Update metadata:**
 165     ```toml
 166     [meta]
 167     generated_by = "2.8.3"  # Change from "1.2.0"
 168     ```
 169  
 170  **Impact Assessment:**
 171  - **Risk:** High (app may fail to start)
 172  - **Effort:** 30 minutes
 173  - **Testing:** Immediate validation required
 174  - **Rollback:** Restore from `.chainlit/config.toml.backup`
 175  
 176  #### 🟠 HIGH: Authentication Changes
 177  
 178  **What Changed:**
 179  - Backend now uses **cookie-based authentication** instead of direct JWT
 180  - More secure (httpOnly cookies, CSRF protection)
 181  - No code changes required for basic password auth
 182  
 183  **Your Code Status:**
 184  ```python
 185  # app.py:143-152 - Password Auth
 186  @cl.password_auth_callback
 187  def auth_callback(username: str, password: str):
 188      # ✅ This will work as-is
 189      return cl.User(...)
 190  
 191  # app.py:132-140 - OAuth
 192  @maybe_oauth_callback
 193  def oauth_callback(provider_id, token, raw_user_data, default_user):
 194      # ✅ This will work as-is
 195      return default_user
 196  ```
 197  
 198  **Testing Required:**
 199  - [ ] Login with password (admin/admin)
 200  - [ ] OAuth flow (if configured)
 201  - [ ] Session persistence across page reloads
 202  - [ ] Logout functionality
 203  - [ ] Cookie security headers present
 204  
 205  #### 🟠 MEDIUM: Actions API Changes
 206  
 207  **Only applies if using `cl.Action`**
 208  
 209  **Status:** ✅ **NOT USED** in your codebase
 210  
 211  **Reference for future:**
 212  ```python
 213  # OLD (1.3.1):
 214  cl.Action(name="...", value="string", description="...")
 215  
 216  # NEW (2.8.3):
 217  cl.Action(
 218      name="...",
 219      payload={"key": "value"},  # Now accepts dict
 220      tooltip="...",             # Renamed from description
 221      icon="MessageSquare"       # NEW: Lucide icons
 222  )
 223  ```
 224  
 225  #### 🟡 MEDIUM: Session Object Changes
 226  
 227  **What Changed:**
 228  ```python
 229  # OLD (1.3.1):
 230  cl.context.session.http_referer   # ❌ Removed
 231  cl.context.session.http_cookie    # ❌ Removed
 232  cl.context.session.languages      # ❌ Removed
 233  
 234  # NEW (2.8.3):
 235  cl.context.session.environ        # ✅ Contains all HTTP headers
 236  ```
 237  
 238  **Your Code Status:**
 239  ```python
 240  # app.py:59, 166, 173, 179
 241  thread_id = cl.context.session.thread_id        # ✅ Still works
 242  chat_profile = cl.context.session.chat_profile  # ✅ Still works
 243  ```
 244  
 245  **Impact:** ✅ **NONE** - You only access `thread_id` and `chat_profile`
 246  
 247  #### 🟡 LOW: UI Rewrite (Shadcn/Tailwind)
 248  
 249  **What Changed:**
 250  - Complete frontend rewrite with Shadcn/Tailwind
 251  - New custom element feature
 252  - Better theme customization
 253  - Cleaner codebase
 254  
 255  **Impact on Your App:**
 256  - Visual appearance may have minor differences
 257  - Custom CSS may need adjustments (if used)
 258  - Better performance and UX
 259  
 260  **Testing Required:**
 261  - [ ] All UI elements render correctly
 262  - [ ] Chat input/output working
 263  - [ ] File upload UI functional
 264  - [ ] Settings panel displays properly
 265  - [ ] Dark/light theme switching
 266  - [ ] Mobile responsiveness
 267  
 268  #### 🟢 LOW: Security Updates
 269  
 270  **Required Updates:**
 271  - FastAPI >= 0.115.3 (CVE-2024-47874 fix)
 272  - Starlette >= 0.41.2
 273  - Python 3.8 support dropped (you're on 3.10 ✅)
 274  
 275  **Impact:** Automatic via dependency resolution
 276  
 277  ---
 278  
 279  ### LangGraph 0.2.45 → 1.0.1
 280  
 281  #### ✅ EXCELLENT NEWS: Backward Compatible!
 282  
 283  **Official Statement:**
 284  > "LangGraph 1.0 maintains full backward compatibility with 0.6.6+. No breaking changes until 2.0."
 285  
 286  **Your Code Status:**
 287  
 288  ```python
 289  # chat_workflow/workflows/base.py
 290  from langgraph.graph import StateGraph, END  # ✅ Still works
 291  
 292  class BaseState(TypedDict):
 293      messages: Annotated[Sequence[AnyMessage], operator.add]  # ✅ Still works
 294      chat_profile: str
 295  
 296  class BaseWorkflow(ABC):
 297      def create_graph(self) -> StateGraph:  # ✅ Still works
 298          graph = StateGraph(MyState)
 299          graph.add_node("chat", self.chat_node)
 300          graph.add_edge("chat", END)
 301          return graph
 302  
 303  # app.py:213
 304  graph.astream_events(state, version="v1", stream_mode="values")  # ✅ Still works
 305  ```
 306  
 307  **Impact:** ✅ **ZERO CODE CHANGES REQUIRED**
 308  
 309  #### ⚠️ DEPRECATED: langgraph.prebuilt
 310  
 311  **What Changed:**
 312  ```python
 313  # ❌ DEPRECATED (still works but will be removed in 2.0):
 314  from langgraph.prebuilt import create_react_agent
 315  
 316  # ✅ NEW LOCATION:
 317  from langchain.agents import create_react_agent
 318  ```
 319  
 320  **Your Code Status:**
 321  ```bash
 322  $ grep -r "langgraph.prebuilt" chat_workflow/
 323  # No matches found ✅
 324  ```
 325  
 326  **Impact:** ✅ **NONE** - You don't use prebuilt agents
 327  
 328  #### 🆕 NEW FEATURES (Optional)
 329  
 330  **Available in LangGraph 1.0:**
 331  
 332  1. **Node Caching** - Skip redundant computations
 333     ```python
 334     graph.add_node("expensive_node", compute_heavy_fn, cache=True)
 335     ```
 336  
 337  2. **Deferred Nodes** - Delay execution until all upstream paths complete
 338     ```python
 339     graph.add_node("summarize", summarize_fn, deferred=True)
 340     ```
 341  
 342  3. **Command API** - Dynamic, edgeless agent flows
 343     ```python
 344     from langgraph.types import Command
 345     # More flexible than traditional edges
 346     ```
 347  
 348  4. **Tool State Updates** - Tools can directly modify graph state
 349     ```python
 350     def tool_with_state_update(state):
 351         # Tool can return state modifications
 352         return {"result": "...", "state_update": {...}}
 353     ```
 354  
 355  5. **Supervisor Library** - Hierarchical multi-agent systems
 356     ```python
 357     from langgraph.supervisor import create_supervisor
 358     ```
 359  
 360  **Recommendation:** Explore these features in Phase 8 (post-upgrade optimization)
 361  
 362  ---
 363  
 364  ## Phase-by-Phase Execution Plan
 365  
 366  ### PHASE 0: Preparation & Backup
 367  **Duration:** 2-3 hours
 368  **Risk:** Low
 369  **Blocking:** None
 370  
 371  #### Checklist
 372  
 373  - [ ] **0.1 Verify Current State**
 374    ```bash
 375    cd /home/user/chainlit_langgraph
 376    git status
 377    git log --oneline -5
 378    docker ps
 379    ```
 380  
 381  - [ ] **0.2 Export Dependencies**
 382    ```bash
 383    poetry export -f requirements.txt -o requirements-backup-v0.3.1.txt --without-hashes
 384    poetry show > poetry-show-backup-v0.3.1.txt
 385    ```
 386  
 387  - [ ] **0.3 Backup Configuration**
 388    ```bash
 389    cp .chainlit/config.toml .chainlit/config.toml.backup
 390    cp pyproject.toml pyproject.toml.backup
 391    cp poetry.lock poetry.lock.backup
 392    ```
 393  
 394  - [ ] **0.4 Database Backup**
 395    ```bash
 396    # Start database if not running
 397    docker compose up -d postgres
 398  
 399    # Create backup
 400    docker exec postgres pg_dump -U postgres postgres > backup-pre-upgrade-$(date +%Y%m%d).sql
 401  
 402    # Verify backup
 403    ls -lh backup-pre-upgrade-*.sql
 404    ```
 405  
 406  - [ ] **0.5 Test Current System**
 407    ```bash
 408    # Run existing tests
 409    poetry run pytest -v
 410  
 411    # Start application
 412    docker compose up -d
 413    curl http://localhost:8000
 414  
 415    # Take screenshots of UI
 416    # Document current behavior
 417    ```
 418  
 419  - [ ] **0.6 Create Rollback Script**
 420    ```bash
 421    cat > rollback.sh << 'EOF'
 422    #!/bin/bash
 423    echo "🔄 Rolling back to v0.3.1..."
 424  
 425    # Restore config files
 426    cp .chainlit/config.toml.backup .chainlit/config.toml
 427    cp pyproject.toml.backup pyproject.toml
 428    cp poetry.lock.backup poetry.lock
 429  
 430    # Restore dependencies
 431    poetry install
 432  
 433    # Restore database
 434    docker exec -i postgres psql -U postgres postgres < backup-pre-upgrade-*.sql
 435  
 436    echo "✅ Rollback complete!"
 437    EOF
 438    chmod +x rollback.sh
 439    ```
 440  
 441  ---
 442  
 443  ### PHASE 1: Dependency Upgrades
 444  **Duration:** 3-4 hours
 445  **Risk:** Medium
 446  **Blocking:** Phase 0
 447  
 448  #### Step 1.1: Update LangGraph (Lower Risk First)
 449  
 450  - [ ] **Update pyproject.toml:**
 451    ```toml
 452    [tool.poetry.dependencies]
 453    langgraph = "^1.0.1"  # Was: "^0.2.31"
 454    ```
 455  
 456  - [ ] **Lock and install:**
 457    ```bash
 458    poetry lock --no-update
 459    poetry install
 460    ```
 461  
 462  - [ ] **Verify installation:**
 463    ```bash
 464    poetry show langgraph
 465    # Should show 1.0.1
 466    ```
 467  
 468  - [ ] **Test import:**
 469    ```bash
 470    poetry run python -c "
 471    from langgraph.graph import StateGraph, END
 472    from langgraph import __version__
 473    print(f'✅ LangGraph {__version__} imported successfully')
 474    "
 475    ```
 476  
 477  - [ ] **Test workflow compilation:**
 478    ```bash
 479    poetry run python -c "
 480    from chat_workflow.workflows.simple_chat import SimpleChatWorkflow
 481    workflow = SimpleChatWorkflow()
 482    graph = workflow.create_graph()
 483    compiled = graph.compile()
 484    print('✅ Graph compiles successfully')
 485    "
 486    ```
 487  
 488  - [ ] **Run tests:**
 489    ```bash
 490    poetry run pytest chat_workflow/tests/test_simple_chat.py -v
 491    ```
 492  
 493  **Expected Result:** ✅ All tests pass (backward compatible)
 494  
 495  #### Step 1.2: Update Chainlit (Higher Risk)
 496  
 497  - [ ] **Update pyproject.toml:**
 498    ```toml
 499    [tool.poetry.dependencies]
 500    chainlit = "^2.8.3"  # Was: "1.3.1"
 501    ```
 502  
 503  - [ ] **Lock and install:**
 504    ```bash
 505    poetry lock
 506    poetry install
 507    ```
 508  
 509  - [ ] **Verify installation:**
 510    ```bash
 511    poetry show chainlit
 512    # Should show 2.8.3
 513    ```
 514  
 515  - [ ] **Test import:**
 516    ```bash
 517    poetry run python -c "
 518    import chainlit as cl
 519    from chainlit import __version__
 520    print(f'✅ Chainlit {__version__} imported successfully')
 521    "
 522    ```
 523  
 524  **Expected Result:** ✅ May show deprecation warnings about config (normal)
 525  
 526  #### Step 1.3: Update LangChain Packages
 527  
 528  - [ ] **Update pyproject.toml:**
 529    ```toml
 530    [tool.poetry.dependencies]
 531    langchain-openai = "^0.3.0"      # Was: "^0.2.1"
 532    langchain-anthropic = "^0.3.0"   # Was: "^0.2.1"
 533    # Others remain the same
 534    ```
 535  
 536  - [ ] **Lock and install:**
 537    ```bash
 538    poetry lock
 539    poetry install
 540    ```
 541  
 542  - [ ] **Test LLM factory:**
 543    ```bash
 544    poetry run python -c "
 545    from chat_workflow.llm.factory import llm_factory
 546    from chat_workflow.llm.providers.openai import OpenAIProvider
 547    print('✅ LLM providers loaded successfully')
 548    print(f'Registered providers: {list(llm_factory._providers.keys())}')
 549    "
 550    ```
 551  
 552  #### Step 1.4: Verify All Dependencies
 553  
 554  - [ ] **Check dependency tree:**
 555    ```bash
 556    poetry show --tree | grep -E "(chainlit|langgraph|langchain)"
 557    ```
 558  
 559  - [ ] **Check for conflicts:**
 560    ```bash
 561    poetry check
 562    ```
 563  
 564  - [ ] **Export new lockfile:**
 565    ```bash
 566    poetry export -f requirements.txt -o requirements-upgraded-v0.4.0.txt --without-hashes
 567    ```
 568  
 569  ---
 570  
 571  ### PHASE 2: Configuration Migration
 572  **Duration:** 2-3 hours
 573  **Risk:** High
 574  **Blocking:** Phase 1
 575  
 576  #### Step 2.1: Update .chainlit/config.toml
 577  
 578  - [ ] **Create backup:**
 579    ```bash
 580    cp .chainlit/config.toml .chainlit/config.toml.pre-migration
 581    ```
 582  
 583  - [ ] **Remove deprecated lines:**
 584    ```bash
 585    # Edit .chainlit/config.toml
 586    # Delete or ensure commented out:
 587    # - Line 19: follow_symlink
 588    # - Line 80: custom_font
 589    # - Lines 41-53: [features.audio] section
 590    # - Lines 90-119: [UI.theme] section
 591    ```
 592  
 593  - [ ] **Update [UI] section to keep only:**
 594    ```toml
 595    [UI]
 596    name = "Assistant"
 597    default_collapse_content = true
 598    cot = "full"
 599    ```
 600  
 601  - [ ] **Update [meta] section:**
 602    ```toml
 603    [meta]
 604    generated_by = "2.8.3"
 605    ```
 606  
 607  - [ ] **Verify final config:**
 608    ```bash
 609    cat .chainlit/config.toml | grep -E "^\[|^[a-z]" | head -20
 610    ```
 611  
 612  **Expected sections remaining:**
 613  - `[project]`
 614  - `[features]`
 615  - `[features.spontaneous_file_upload]`
 616  - `[UI]`
 617  - `[meta]`
 618  
 619  #### Step 2.2: Create Theme File (Optional)
 620  
 621  If you want custom theming:
 622  
 623  - [ ] **Create .chainlit/theme.json:**
 624    ```bash
 625    cat > .chainlit/theme.json << 'EOF'
 626    {
 627      "default": "dark",
 628      "light": {
 629        "primary": {
 630          "main": "#F80061",
 631          "dark": "#980039",
 632          "light": "#FFE7EB"
 633        },
 634        "text": {
 635          "primary": "#212121",
 636          "secondary": "#616161"
 637        },
 638        "background": "#FAFAFA",
 639        "paper": "#FFFFFF"
 640      },
 641      "dark": {
 642        "primary": {
 643          "main": "#F80061",
 644          "dark": "#980039",
 645          "light": "#FFE7EB"
 646        },
 647        "text": {
 648          "primary": "#EEEEEE",
 649          "secondary": "#BDBDBD"
 650        },
 651        "background": "#121212",
 652        "paper": "#1E1E1E"
 653      }
 654    }
 655    EOF
 656    ```
 657  
 658  - [ ] **Verify JSON syntax:**
 659    ```bash
 660    python -m json.tool .chainlit/theme.json > /dev/null && echo "✅ Valid JSON"
 661    ```
 662  
 663  #### Step 2.3: Test Configuration
 664  
 665  - [ ] **Start application:**
 666    ```bash
 667    poetry run chainlit run app.py --port 8001
 668    ```
 669  
 670  - [ ] **Check for config errors:**
 671    ```bash
 672    # Look for startup errors
 673    # Should see: "Chainlit is running at http://localhost:8001"
 674    # Should NOT see: "Unknown config field" or "Invalid config"
 675    ```
 676  
 677  - [ ] **Test in browser:**
 678    ```
 679    Open http://localhost:8001
 680    Check console for errors
 681    Verify theme loads correctly
 682    ```
 683  
 684  ---
 685  
 686  ### PHASE 3: Code Migration
 687  **Duration:** 4-6 hours
 688  **Risk:** Medium
 689  **Blocking:** Phase 1
 690  
 691  #### Step 3.1: Verify Imports
 692  
 693  - [ ] **Check for langgraph.prebuilt usage:**
 694    ```bash
 695    grep -r "from langgraph.prebuilt" chat_workflow/
 696    grep -r "import langgraph.prebuilt" chat_workflow/
 697    grep -r "create_react_agent" chat_workflow/
 698    ```
 699  
 700  **Expected:** No matches found ✅
 701  
 702  - [ ] **Test all imports:**
 703    ```bash
 704    poetry run python -c "
 705    import app
 706    from chat_workflow.workflows.base import BaseWorkflow, BaseState
 707    from chat_workflow.workflows.simple_chat import SimpleChatWorkflow
 708    from chat_workflow.workflows.multimodal_chat import MultimodalChatWorkflow
 709    from chat_workflow.workflows.resume_optimizer import ResumeOptimizerWorkflow
 710    from chat_workflow.workflows.lean_canvas_chat import LeanCanvasChatWorkflow
 711    print('✅ All imports successful')
 712    "
 713    ```
 714  
 715  #### Step 3.2: Validate Storage Client
 716  
 717  - [ ] **Test MinIO storage client:**
 718    ```bash
 719    poetry run python -c "
 720    from chainlit.data.base import BaseStorageClient
 721    from chat_workflow.storage_client import MinIOStorageClient
 722    print('✅ Storage client inherits from correct base class')
 723    "
 724    ```
 725  
 726  - [ ] **Check upload_file signature:**
 727    ```bash
 728    poetry run python -c "
 729    import inspect
 730    from chat_workflow.storage_client import MinIOStorageClient
 731    sig = inspect.signature(MinIOStorageClient.upload_file)
 732    print(f'upload_file signature: {sig}')
 733    # Verify parameters match BaseStorageClient interface
 734    "
 735    ```
 736  
 737  #### Step 3.3: Validate Session Access
 738  
 739  Your code only accesses:
 740  - `cl.context.session.thread_id` ✅ Still available
 741  - `cl.context.session.chat_profile` ✅ Still available
 742  
 743  - [ ] **Test session access:**
 744    ```python
 745    # Add to test file or run manually after startup
 746    # Verify these work in @cl.on_chat_start:
 747    thread_id = cl.context.session.thread_id
 748    chat_profile = cl.context.session.chat_profile
 749    ```
 750  
 751  No changes required ✅
 752  
 753  #### Step 3.4: Validate Authentication
 754  
 755  - [ ] **Test password auth callback signature:**
 756    ```bash
 757    poetry run python -c "
 758    import inspect
 759    from app import auth_callback
 760    sig = inspect.signature(auth_callback)
 761    print(f'auth_callback signature: {sig}')
 762    # Should be: (username: str, password: str)
 763    "
 764    ```
 765  
 766  - [ ] **Test OAuth callback signature:**
 767    ```bash
 768    poetry run python -c "
 769    import inspect
 770    from app import oauth_callback
 771    sig = inspect.signature(oauth_callback)
 772    print(f'oauth_callback signature: {sig}')
 773    # Should be: (provider_id, token, raw_user_data, default_user)
 774    "
 775    ```
 776  
 777  No changes required ✅
 778  
 779  #### Step 3.5: Validate Workflow Patterns
 780  
 781  - [ ] **Test all workflows compile:**
 782    ```bash
 783    poetry run python << 'EOF'
 784    from chat_workflow.workflows.workflow_factory import WorkflowFactory
 785    from chat_workflow.module_discovery import discover_workflows
 786  
 787    discover_workflows()
 788    workflows = WorkflowFactory.list_workflows()
 789    print(f"Found {len(workflows)} workflows: {workflows}")
 790  
 791    for name in workflows:
 792        workflow = WorkflowFactory.create(name)
 793        graph = workflow.create_graph()
 794        compiled = graph.compile()
 795        print(f"✅ {name} compiles successfully")
 796    EOF
 797    ```
 798  
 799  ---
 800  
 801  ### PHASE 4: Database Schema Validation
 802  **Duration:** 2 hours
 803  **Risk:** Medium
 804  **Blocking:** Phase 3
 805  
 806  #### Step 4.1: Check Chainlit Schema
 807  
 808  - [ ] **Start database:**
 809    ```bash
 810    docker compose up -d postgres
 811    ```
 812  
 813  - [ ] **List current tables:**
 814    ```bash
 815    docker exec postgres psql -U postgres -d postgres -c "\dt"
 816    ```
 817  
 818  **Expected tables:**
 819  - `users`
 820  - `threads`
 821  - `steps`
 822  - `elements`
 823  - `feedbacks`
 824  - `langgraphs` (custom)
 825  
 826  - [ ] **Check Chainlit migrations:**
 827    ```bash
 828    docker exec postgres psql -U postgres -d postgres -c "
 829    SELECT version_num, description
 830    FROM alembic_version;
 831    "
 832    ```
 833  
 834  #### Step 4.2: Test Alembic Migrations
 835  
 836  - [ ] **Check for new migrations:**
 837    ```bash
 838    poetry run alembic heads
 839    poetry run alembic current
 840    ```
 841  
 842  - [ ] **Generate migration if needed:**
 843    ```bash
 844    poetry run alembic revision --autogenerate -m "upgrade_chainlit_2_8_3"
 845    ```
 846  
 847  - [ ] **Review generated migration:**
 848    ```bash
 849    # Check alembic/versions/ for new file
 850    # Review SQL statements
 851    # Ensure no destructive changes to langgraphs table
 852    ```
 853  
 854  - [ ] **Apply migration (if generated):**
 855    ```bash
 856    poetry run alembic upgrade head
 857    ```
 858  
 859  #### Step 4.3: Validate Custom Tables
 860  
 861  - [ ] **Check langgraphs table:**
 862    ```bash
 863    docker exec postgres psql -U postgres -d postgres -c "
 864    \d langgraphs
 865    "
 866    ```
 867  
 868  **Expected columns:**
 869  - `thread_id` (String, PK)
 870  - `state` (JSON)
 871  - `workflow` (String)
 872  
 873  - [ ] **Test data integrity:**
 874    ```bash
 875    docker exec postgres psql -U postgres -d postgres -c "
 876    SELECT COUNT(*) as total_graphs,
 877           COUNT(DISTINCT workflow) as unique_workflows
 878    FROM langgraphs;
 879    "
 880    ```
 881  
 882  #### Step 4.4: Test State Serialization
 883  
 884  - [ ] **Test serialization roundtrip:**
 885    ```bash
 886    poetry run python << 'EOF'
 887    from chat_workflow.state_serializer import StateSerializer
 888    from chat_workflow.workflows.base import BaseState
 889    from langchain_core.messages import HumanMessage, AIMessage
 890  
 891    # Create test state
 892    test_state = {
 893        "messages": [
 894            HumanMessage(content="Hello"),
 895            AIMessage(content="Hi there!")
 896        ],
 897        "chat_profile": "simple_chat"
 898    }
 899  
 900    # Serialize
 901    serialized = StateSerializer.serialize(test_state)
 902    print(f"Serialized: {serialized}")
 903  
 904    # Deserialize
 905    deserialized = StateSerializer.deserialize(serialized, BaseState)
 906    print(f"Deserialized: {deserialized}")
 907  
 908    # Verify
 909    assert len(deserialized["messages"]) == 2
 910    assert deserialized["messages"][0].content == "Hello"
 911    print("✅ Serialization roundtrip successful")
 912    EOF
 913    ```
 914  
 915  ---
 916  
 917  ### PHASE 5: Testing & Validation
 918  **Duration:** 8 hours
 919  **Risk:** N/A (validation phase)
 920  **Blocking:** Phases 1-4
 921  
 922  #### Step 5.1: Unit Tests
 923  
 924  - [ ] **Run full test suite:**
 925    ```bash
 926    poetry run pytest -v --tb=short
 927    ```
 928  
 929  - [ ] **Test LLM module:**
 930    ```bash
 931    poetry run pytest chat_workflow/tests/test_llm.py -v
 932    ```
 933  
 934  - [ ] **Test workflows:**
 935    ```bash
 936    poetry run pytest chat_workflow/tests/test_simple_chat.py -v
 937    ```
 938  
 939  - [ ] **Check test coverage:**
 940    ```bash
 941    poetry run pytest --cov=chat_workflow --cov-report=html
 942    ```
 943  
 944  #### Step 5.2: Integration Testing - Application Startup
 945  
 946  - [ ] **Test 1: Start services:**
 947    ```bash
 948    docker compose up -d postgres minio
 949    poetry run chainlit run app.py --port 8000
 950    ```
 951  
 952  **Expected output:**
 953  ```
 954  Your app is available at http://localhost:8000
 955  Chat profiles created: 4
 956  ```
 957  
 958  - [ ] **Test 2: Check logs:**
 959    ```bash
 960    # No ERROR messages
 961    # Look for: "Logging level set to: INFO"
 962    # Look for: "Chat profiles created: 4"
 963    # Look for: "MinIOStorageClient initialized"
 964    ```
 965  
 966  - [ ] **Test 3: Access UI:**
 967    ```
 968    Open http://localhost:8000
 969    - Page loads without errors
 970    - Login screen appears
 971    - No console errors in browser devtools
 972    ```
 973  
 974  #### Step 5.3: Authentication Testing
 975  
 976  - [ ] **Test 4: Password login:**
 977    ```
 978    Username: admin
 979    Password: admin
 980    Expected: ✅ Login successful, redirect to chat
 981    ```
 982  
 983  - [ ] **Test 5: Check session:**
 984    ```
 985    - Refresh page → Still logged in
 986    - Check browser cookies → chainlit session cookie present
 987    - Check cookie attributes → httpOnly, secure (if HTTPS)
 988    ```
 989  
 990  - [ ] **Test 6: Logout (if available):**
 991    ```
 992    - Logout → Redirect to login
 993    - Try to access chat → Redirect to login
 994    ```
 995  
 996  - [ ] **Test 7: OAuth (if configured):**
 997    ```
 998    - Click OAuth provider
 999    - Complete OAuth flow
1000    - Return to app logged in
1001    ```
1002  
1003  #### Step 5.4: Workflow Testing
1004  
1005  - [ ] **Test 8: Workflow discovery:**
1006    ```
1007    - Click chat profile selector
1008    - See 4 workflows:
1009      1. Simple Chat
1010      2. Multimodal Chat
1011      3. Resume Optimizer
1012      4. Lean Canvas Chat
1013    ```
1014  
1015  - [ ] **Test 9: Simple Chat workflow:**
1016    ```
1017    1. Select "Simple Chat"
1018    2. Check settings panel:
1019       - Model selector appears
1020       - Multiple models listed
1021    3. Send message: "What's 2+2?"
1022    4. Expected:
1023       - Message appears in chat
1024       - Streaming response (token by token)
1025       - AI responds with answer
1026       - No errors in logs
1027    ```
1028  
1029  - [ ] **Test 10: Tool calling:**
1030    ```
1031    1. In Simple Chat, send: "What time is it?"
1032    2. Expected:
1033       - Tool call to datetime tool
1034       - Tool result appears
1035       - AI responds with current time
1036    3. Send: "Search web for latest AI news"
1037    4. Expected (if TAVILY_API_KEY set):
1038       - Tool call to search tool
1039       - Search results appear
1040       - AI summarizes results
1041    ```
1042  
1043  - [ ] **Test 11: Settings update:**
1044    ```
1045    1. Change model in settings (e.g., GPT-4 → Claude)
1046    2. Send new message
1047    3. Expected:
1048       - New model used for response
1049       - Response style may differ
1050    4. Check logs:
1051       - "Updating state based on new settings"
1052       - "Setting chat_model to [new model]"
1053    ```
1054  
1055  #### Step 5.5: State Persistence Testing
1056  
1057  - [ ] **Test 12: Chat state persistence:**
1058    ```
1059    1. Start new chat
1060    2. Send 3-4 messages
1061    3. Refresh page
1062    4. Expected:
1063       - Chat history restored
1064       - All messages visible
1065       - Can continue conversation
1066    ```
1067  
1068  - [ ] **Test 13: Resume from database:**
1069    ```
1070    1. Send messages in chat
1071    2. Close browser tab completely
1072    3. Open new tab → http://localhost:8000
1073    4. Navigate to previous thread (if UI allows)
1074    5. Expected:
1075       - Full chat history loaded
1076       - Correct workflow active
1077       - Settings restored
1078    ```
1079  
1080  - [ ] **Test 14: Database query:**
1081    ```bash
1082    docker exec postgres psql -U postgres -d postgres -c "
1083    SELECT thread_id, workflow,
1084           jsonb_array_length(state->'messages') as msg_count
1085    FROM langgraphs
1086    ORDER BY thread_id DESC
1087    LIMIT 5;
1088    "
1089    ```
1090    Expected: Recent threads with message counts
1091  
1092  #### Step 5.6: File Upload Testing
1093  
1094  - [ ] **Test 15: Resume Optimizer workflow:**
1095    ```
1096    1. Select "Resume Optimizer" profile
1097    2. Expected: Prompt to upload PDF
1098    3. Upload sample PDF resume
1099    4. Expected:
1100       - File uploaded to MinIO
1101       - PDF extracted successfully
1102       - AI provides resume analysis
1103    ```
1104  
1105  - [ ] **Test 16: MinIO storage:**
1106    ```bash
1107    # Check file in MinIO
1108    docker exec minio mc ls myminio/mybucket/
1109    ```
1110  
1111  - [ ] **Test 17: Multimodal Chat with image:**
1112    ```
1113    1. Select "Multimodal Chat" profile
1114    2. Upload image file (PNG/JPG)
1115    3. Add text: "What's in this image?"
1116    4. Expected:
1117       - Image uploaded
1118       - Image displayed in chat
1119       - AI describes image content
1120    ```
1121  
1122  #### Step 5.7: UI Testing
1123  
1124  - [ ] **Test 18: Theme switching:**
1125    ```
1126    - Find theme toggle (if available)
1127    - Switch light ↔ dark
1128    - Expected: Colors change smoothly
1129    ```
1130  
1131  - [ ] **Test 19: Responsive design:**
1132    ```
1133    - Resize browser window
1134    - Test on mobile screen size
1135    - Expected: Layout adapts
1136    ```
1137  
1138  - [ ] **Test 20: All UI elements:**
1139    ```
1140    - Chat input field works
1141    - Send button works
1142    - File upload button works
1143    - Settings panel opens/closes
1144    - Profile selector works
1145    - No visual glitches
1146    ```
1147  
1148  #### Step 5.8: Error Handling
1149  
1150  - [ ] **Test 21: Invalid API key:**
1151    ```
1152    1. Remove API key from .env
1153    2. Try to send message with that provider
1154    3. Expected: Error message shown to user
1155    ```
1156  
1157  - [ ] **Test 22: Network error:**
1158    ```
1159    1. Stop MinIO: docker compose stop minio
1160    2. Try to upload file
1161    3. Expected: Error handled gracefully
1162    4. Start MinIO: docker compose start minio
1163    ```
1164  
1165  - [ ] **Test 23: Database connection loss:**
1166    ```
1167    1. Stop PostgreSQL briefly
1168    2. Try to start new chat
1169    3. Expected: Error message or retry logic
1170    ```
1171  
1172  #### Step 5.9: Performance Testing
1173  
1174  - [ ] **Test 24: Response time:**
1175    ```
1176    - Send message
1177    - Measure time to first token
1178    - Expected: < 2 seconds
1179    ```
1180  
1181  - [ ] **Test 25: Streaming performance:**
1182    ```
1183    - Send message requesting long response
1184    - Observe streaming
1185    - Expected: Smooth, no delays between tokens
1186    ```
1187  
1188  - [ ] **Test 26: Memory usage:**
1189    ```bash
1190    docker stats --no-stream
1191    # Check chainlit container memory
1192    # Expected: Reasonable (< 2GB for normal usage)
1193    ```
1194  
1195  ---
1196  
1197  ### PHASE 6: Docker & Deployment Updates
1198  **Duration:** 3-4 hours
1199  **Risk:** Low
1200  **Blocking:** Phase 5
1201  
1202  #### Step 6.1: Update Dockerfile (Optional)
1203  
1204  - [ ] **Consider Python version upgrade:**
1205    ```dockerfile
1206    FROM python:3.11-slim  # Change from 3.10-slim
1207    ```
1208  
1209  - [ ] **Verify system dependencies:**
1210    ```dockerfile
1211    RUN apt-get update && apt-get install -y --no-install-recommends \
1212        build-essential \
1213        libpq-dev \
1214        libsndfile1 \
1215        curl \  # For healthcheck
1216        && rm -rf /var/lib/apt/lists/*
1217    ```
1218  
1219  - [ ] **Add healthcheck:**
1220    ```dockerfile
1221    HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
1222      CMD curl -f http://localhost:8000/health || exit 1
1223    ```
1224  
1225  #### Step 6.2: Update docker-compose.yml
1226  
1227  - [ ] **Add healthchecks:**
1228    ```yaml
1229    services:
1230      chainlit:
1231        healthcheck:
1232          test: ["CMD", "curl", "-f", "http://localhost:8000"]
1233          interval: 30s
1234          timeout: 10s
1235          retries: 3
1236          start_period: 10s
1237  
1238      postgres:
1239        healthcheck:
1240          test: ["CMD-SHELL", "pg_isready -U postgres"]
1241          interval: 10s
1242          timeout: 5s
1243          retries: 5
1244  
1245      minio:
1246        healthcheck:
1247          test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
1248          interval: 30s
1249          timeout: 10s
1250          retries: 3
1251    ```
1252  
1253  - [ ] **Add depends_on with conditions:**
1254    ```yaml
1255    services:
1256      chainlit:
1257        depends_on:
1258          postgres:
1259            condition: service_healthy
1260          minio:
1261            condition: service_healthy
1262    ```
1263  
1264  #### Step 6.3: Test Docker Build
1265  
1266  - [ ] **Clean build:**
1267    ```bash
1268    docker compose down -v
1269    docker compose build --no-cache
1270    ```
1271  
1272  - [ ] **Start all services:**
1273    ```bash
1274    docker compose up
1275    ```
1276  
1277  - [ ] **Check healthchecks:**
1278    ```bash
1279    docker compose ps
1280    # All services should show (healthy)
1281    ```
1282  
1283  - [ ] **Test application in Docker:**
1284    ```bash
1285    curl http://localhost:8000
1286    # Should return HTML
1287    ```
1288  
1289  #### Step 6.4: Production Deployment Checklist
1290  
1291  - [ ] **Environment variables:**
1292    ```bash
1293    # Verify all required vars in .env:
1294    grep -E "^[A-Z_]+=" .env | wc -l
1295    ```
1296  
1297  - [ ] **Secrets management:**
1298    ```
1299    - CHAINLIT_AUTH_SECRET set to strong random value
1300    - API keys not hardcoded
1301    - Database passwords secure
1302    ```
1303  
1304  - [ ] **Volume persistence:**
1305    ```bash
1306    # Verify volumes configured in docker-compose.yml
1307    docker volume ls
1308    ```
1309  
1310  - [ ] **Backup strategy:**
1311    ```bash
1312    # Document backup procedure
1313    # Test restore procedure
1314    ```
1315  
1316  - [ ] **Monitoring:**
1317    ```
1318    - Log aggregation configured
1319    - Error alerting set up
1320    - Performance metrics collected
1321    ```
1322  
1323  ---
1324  
1325  ### PHASE 7: Documentation Updates
1326  **Duration:** 2-3 hours
1327  **Risk:** Low
1328  **Blocking:** Phase 6 (can parallelize after Phase 5)
1329  
1330  #### Step 7.1: Update README.md
1331  
1332  - [ ] **Update version badges:**
1333    ```markdown
1334    [![Version](https://img.shields.io/badge/Version-0.4.0-blue)](https://github.com/brucechou1983/chainlit-langgraph)
1335    [![Chainlit](https://img.shields.io/badge/Chainlit-2.8.3-brightgreen)](https://github.com/Chainlit/chainlit)
1336    [![LangGraph](https://img.shields.io/badge/LangGraph-1.0.1-brightgreen)](https://github.com/langchain-ai/langgraph)
1337    ```
1338  
1339  - [ ] **Add migration notice:**
1340    ```markdown
1341    ## Migration Notes
1342  
1343    ### Version 0.4.0 (Breaking Changes)
1344  
1345    This version includes major upgrades:
1346    - Chainlit 1.3.1 → 2.8.3
1347    - LangGraph 0.2.45 → 1.0.1
1348  
1349    If upgrading from v0.3.x, please read [MIGRATION.md](MIGRATION.md) for detailed instructions.
1350  
1351    **Key Changes:**
1352    - Configuration file structure updated
1353    - Python 3.8 no longer supported (minimum 3.10)
1354    - Theme customization moved to separate file
1355    - New security features with cookie-based auth
1356    ```
1357  
1358  - [ ] **Update Getting Started:**
1359    ```markdown
1360    ## Requirements
1361    - Python 3.10 or higher
1362    - Docker & Docker Compose
1363    - API keys for LLM providers (optional, can use Ollama)
1364    ```
1365  
1366  #### Step 7.2: Create MIGRATION.md
1367  
1368  - [ ] **Copy this plan document:**
1369    ```bash
1370    # This document serves as MIGRATION.md
1371    # No additional action needed
1372    ```
1373  
1374  #### Step 7.3: Update CHANGELOG.md
1375  
1376  - [ ] **Add new version entry:**
1377    ```markdown
1378    ## [0.4.0] - 2025-10-27
1379  
1380    ### Changed
1381    - **BREAKING:** Upgraded Chainlit from 1.3.1 to 2.8.3
1382    - **BREAKING:** Configuration file structure changed - theme and audio sections removed
1383    - **BREAKING:** Python 3.8 support dropped (minimum Python 3.10)
1384    - Upgraded LangGraph from 0.2.45 to 1.0.1
1385    - Updated LangChain packages to latest compatible versions
1386    - Authentication now uses secure cookie-based system
1387  
1388    ### Added
1389    - Optional theme.json for custom theme configuration
1390    - Improved security with updated FastAPI/Starlette
1391    - Better UI with Shadcn/Tailwind rewrite
1392    - Access to LangGraph 1.0 features (node caching, commands, etc.)
1393  
1394    ### Removed
1395    - Audio configuration from config.toml (use new API if needed)
1396    - Theme configuration from config.toml (moved to theme.json)
1397    - Support for Python 3.8
1398  
1399    ### Migration
1400    - See [MIGRATION.md](MIGRATION.md) for detailed upgrade instructions
1401    - Backup your database before upgrading
1402    - Update your .chainlit/config.toml (remove deprecated sections)
1403    - Test thoroughly after upgrade
1404  
1405    ### Security
1406    - Fixed CVE-2024-47874 via FastAPI/Starlette updates
1407    - Improved authentication security with httpOnly cookies
1408    ```
1409  
1410  #### Step 7.4: Update Version Files
1411  
1412  - [ ] **Update chat_workflow/version.py:**
1413    ```python
1414    __version__ = "0.4.0"
1415    ```
1416  
1417  - [ ] **Update pyproject.toml:**
1418    ```toml
1419    [tool.commitizen]
1420    version = "0.4.0"
1421    ```
1422  
1423  - [ ] **Commit version bump:**
1424    ```bash
1425    git add chat_workflow/version.py pyproject.toml
1426    git commit -m "bump: version 0.3.1 → 0.4.0"
1427    ```
1428  
1429  #### Step 7.5: Update Configuration Documentation
1430  
1431  - [ ] **Document new config structure:**
1432    Create `.chainlit/README.md`:
1433    ```markdown
1434    # Chainlit Configuration
1435  
1436    ## config.toml
1437  
1438    Main configuration file. After upgrade to Chainlit 2.8.3:
1439  
1440    - ❌ Removed: `follow_symlink`, `custom_font`, `audio`, `theme`
1441    - ✅ Kept: `project`, `features`, `UI` (basic settings)
1442  
1443    ## theme.json (Optional)
1444  
1445    Custom theme configuration. Create this file if you want to customize colors.
1446  
1447    Example:
1448    ```json
1449    {
1450      "default": "dark",
1451      "light": { ... },
1452      "dark": { ... }
1453    }
1454    ```
1455  
1456    See: https://docs.chainlit.io/customization/theming
1457    ```
1458  
1459  ---
1460  
1461  ### PHASE 8: Post-Upgrade Optimization (Optional)
1462  **Duration:** Variable
1463  **Risk:** Low
1464  **Blocking:** Phases 1-7 complete
1465  
1466  #### Future Enhancement Opportunities
1467  
1468  - [ ] **Leverage LangGraph 1.0 Features:**
1469  
1470    **Node Caching:**
1471    ```python
1472    # Add caching to expensive nodes
1473    graph.add_node("expensive_computation", compute_fn, cache=True)
1474    ```
1475  
1476    **Deferred Nodes:**
1477    ```python
1478    # Wait for all upstream paths before summarizing
1479    graph.add_node("final_summary", summarize_fn, deferred=True)
1480    ```
1481  
1482    **Command API:**
1483    ```python
1484    from langgraph.types import Command
1485    # More flexible than traditional edges
1486    ```
1487  
1488  - [ ] **Explore Chainlit 2.0 Features:**
1489  
1490    **Custom Elements:**
1491    ```python
1492    # Create custom UI elements with Shadcn components
1493    ```
1494  
1495    **New Theme System:**
1496    ```python
1497    # Advanced theme customization with theme.json
1498    ```
1499  
1500    **Audio Streaming (if needed):**
1501    ```python
1502    @cl.on_audio_start
1503    async def on_audio_start():
1504        # New audio API
1505    ```
1506  
1507  - [ ] **Python 3.11+ Upgrade:**
1508    ```dockerfile
1509    FROM python:3.11-slim
1510    # Benefits: Better performance, improved error messages
1511    ```
1512  
1513  - [ ] **Performance Optimization:**
1514    - Profile streaming performance
1515    - Optimize database queries
1516    - Add caching layers
1517    - Implement rate limiting
1518  
1519  - [ ] **Security Hardening:**
1520    - Review cookie security settings
1521    - Implement CSP headers
1522    - Add rate limiting
1523    - Audit API key handling
1524  
1525  ---
1526  
1527  ## Rollback Procedures
1528  
1529  ### Quick Rollback (< 5 minutes)
1530  
1531  ```bash
1532  # Run rollback script created in Phase 0
1533  ./rollback.sh
1534  ```
1535  
1536  ### Manual Rollback
1537  
1538  #### Step 1: Restore Dependencies
1539  ```bash
1540  cp pyproject.toml.backup pyproject.toml
1541  cp poetry.lock.backup poetry.lock
1542  poetry install
1543  ```
1544  
1545  #### Step 2: Restore Configuration
1546  ```bash
1547  cp .chainlit/config.toml.backup .chainlit/config.toml
1548  rm .chainlit/theme.json  # If created
1549  ```
1550  
1551  #### Step 3: Restore Database
1552  ```bash
1553  docker exec -i postgres psql -U postgres postgres < backup-pre-upgrade-*.sql
1554  ```
1555  
1556  #### Step 4: Restart Services
1557  ```bash
1558  docker compose down
1559  docker compose up -d
1560  ```
1561  
1562  #### Step 5: Verify
1563  ```bash
1564  curl http://localhost:8000
1565  # Check version in logs
1566  ```
1567  
1568  ### Git Rollback
1569  
1570  ```bash
1571  # If changes committed
1572  git log --oneline
1573  git revert <commit-hash>
1574  git push origin claude/upgrade-chainlit-langraph-011CUXSzH8vJY23G3tyoznkW
1575  ```
1576  
1577  ---
1578  
1579  ## Testing Checklist Summary
1580  
1581  ### Critical Tests (Must Pass)
1582  - [ ] Application starts without errors
1583  - [ ] Authentication works (password + OAuth if configured)
1584  - [ ] All 5 workflows discoverable
1585  - [ ] Can send/receive messages with streaming
1586  - [ ] State persists across sessions
1587  - [ ] Database queries work
1588  - [ ] File uploads work (MinIO)
1589  - [ ] Settings updates apply
1590  
1591  ### Important Tests (Should Pass)
1592  - [ ] All unit tests pass
1593  - [ ] UI renders correctly
1594  - [ ] Dark/light theme works
1595  - [ ] Multimodal chat with images
1596  - [ ] Tool calling works
1597  - [ ] Resume PDF extraction works
1598  - [ ] No console errors
1599  - [ ] Reasonable performance
1600  
1601  ### Nice-to-Have Tests
1602  - [ ] Test coverage maintained
1603  - [ ] Documentation updated
1604  - [ ] Docker build optimized
1605  - [ ] Healthchecks working
1606  - [ ] Monitoring configured
1607  
1608  ---
1609  
1610  ## Risk Matrix
1611  
1612  | Risk | Probability | Impact | Mitigation |
1613  |------|-------------|--------|------------|
1614  | Config file errors | High | High | Backup, test immediately |
1615  | Database schema changes | Low | High | Full backup, test migrations |
1616  | Auth flow breaks | Low | High | Test immediately after upgrade |
1617  | State serialization fails | Low | High | Test with existing data |
1618  | UI rendering issues | Medium | Medium | Visual QA, browser testing |
1619  | Performance degradation | Low | Medium | Benchmark before/after |
1620  | Docker build fails | Low | Medium | Test in stages |
1621  | Loss of features | Low | Low | Full feature testing |
1622  
1623  ---
1624  
1625  ## Success Metrics
1626  
1627  ### Technical Metrics
1628  - ✅ Zero critical errors in logs
1629  - ✅ All tests passing (100%)
1630  - ✅ Response time < 2s (first token)
1631  - ✅ Memory usage < 2GB (normal load)
1632  - ✅ All 5 workflows functional
1633  - ✅ 100% feature parity with v0.3.1
1634  
1635  ### Business Metrics
1636  - ✅ Zero user-reported issues
1637  - ✅ No data loss
1638  - ✅ Same or better UX
1639  - ✅ Improved security posture
1640  
1641  ---
1642  
1643  ## Support Resources
1644  
1645  ### Official Documentation
1646  - [Chainlit 2.0 Migration Guide](https://docs.chainlit.io/guides/migration/2.0.0)
1647  - [Chainlit 2.8.3 Docs](https://docs.chainlit.io/)
1648  - [LangGraph 1.0 Docs](https://langchain-ai.github.io/langgraph/)
1649  - [LangChain 0.3 Docs](https://python.langchain.com/docs/versions/v0_3/)
1650  
1651  ### Community Support
1652  - [Chainlit GitHub Issues](https://github.com/Chainlit/chainlit/issues)
1653  - [Chainlit Discord](https://discord.gg/chainlit)
1654  - [LangChain Discord](https://discord.gg/langchain)
1655  - [LangGraph Discussions](https://github.com/langchain-ai/langgraph/discussions)
1656  
1657  ### Troubleshooting Common Issues
1658  
1659  **Issue:** "Unknown config field" error
1660  - **Solution:** Remove deprecated fields from config.toml
1661  
1662  **Issue:** Authentication not working
1663  - **Solution:** Check CHAINLIT_AUTH_SECRET is set, cookies enabled
1664  
1665  **Issue:** Workflows not loading
1666  - **Solution:** Check module discovery logs, verify imports
1667  
1668  **Issue:** Database connection errors
1669  - **Solution:** Verify PostgreSQL running, check credentials
1670  
1671  **Issue:** MinIO upload fails
1672  - **Solution:** Check MinIO running, bucket exists, credentials correct
1673  
1674  ---
1675  
1676  ## Approval & Sign-off
1677  
1678  **Before proceeding with upgrade:**
1679  
1680  - [ ] All stakeholders informed
1681  - [ ] Backup verified and tested
1682  - [ ] Rollback plan understood
1683  - [ ] Testing environment available
1684  - [ ] Maintenance window scheduled
1685  - [ ] Team members assigned roles
1686  - [ ] Monitoring and alerting ready
1687  - [ ] Communication plan in place
1688  
1689  **Approved by:** _________________
1690  **Date:** _________________
1691  **Scheduled for:** _________________
1692  
1693  ---
1694  
1695  ## Execution Log
1696  
1697  ### Phase 0: Preparation
1698  - Started: __________
1699  - Completed: __________
1700  - Issues: __________
1701  - Notes: __________
1702  
1703  ### Phase 1: Dependencies
1704  - Started: __________
1705  - Completed: __________
1706  - Issues: __________
1707  - Notes: __________
1708  
1709  ### Phase 2: Configuration
1710  - Started: __________
1711  - Completed: __________
1712  - Issues: __________
1713  - Notes: __________
1714  
1715  ### Phase 3: Code Migration
1716  - Started: __________
1717  - Completed: __________
1718  - Issues: __________
1719  - Notes: __________
1720  
1721  ### Phase 4: Database
1722  - Started: __________
1723  - Completed: __________
1724  - Issues: __________
1725  - Notes: __________
1726  
1727  ### Phase 5: Testing
1728  - Started: __________
1729  - Completed: __________
1730  - Issues: __________
1731  - Notes: __________
1732  
1733  ### Phase 6: Docker
1734  - Started: __________
1735  - Completed: __________
1736  - Issues: __________
1737  - Notes: __________
1738  
1739  ### Phase 7: Documentation
1740  - Started: __________
1741  - Completed: __________
1742  - Issues: __________
1743  - Notes: __________
1744  
1745  ---
1746  
1747  ## Post-Upgrade Review
1748  
1749  **Completed:** __________
1750  **Total Duration:** __________
1751  **Issues Encountered:** __________
1752  **Lessons Learned:** __________
1753  **Recommendations:** __________
1754  
1755  ---
1756  
1757  **Document Version:** 1.0
1758  **Last Updated:** 2025-10-27
1759  **Next Review:** After upgrade completion